What steps are involved in designing a comment form that allows for the dynamic addition of comments to a list?

I am looking to implement a form for comments that can be dynamically added to the list. Each comment needs to have a unique ID assigned in sequential order, with the newest comment appearing at the bottom of the list. The comments should be stored in an array called 'comments', which should initially be empty when loaded. When the "Add" button is clicked, a new object should be created in the array and displayed on the webpage.

let nextId = 1;

const comments = [];

const commentForm = document.querySelector('[data-id="comment-form"]');
const commentInput = commentForm.querySelector('[data-input="comment"]');
const button = commentForm.querySelector('[data-action="add"]');
const commentList = commentForm.querySelector('[data-id="comment-list"]');

button.addEventListener('click', () => {
  const object = {};
  if (commentInput.value != '') {
    comments.map(() => ({ id: 'nextId++', text: commentInput.value }));
  }
  createElement();
});

function createElement() {
  const newComment = document.createElement('li');
  newComment.setAttribute('data-comment-id', comments.id);
  newComment.textContent = comments.text;
  commentList.appendChild(newComment);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
    <link rel="stylesheet" href="./css/styles.css" />
  </head>
  <body>
    <div id="root">
      <form data-id="comment-form">
        <textarea data-input="comment"></textarea>
        <button data-action="add">Add</button>
      </form>
      <ul data-id="comment-list"></ul>
    </div>
    <script src="./js/app.js"></script>
  </body>
</html>

Answer №1

There seem to be a few issues in your code:

  1. You are attempting to access the commentList from within commentForm, but that element is located outside of the commentForm. You need to use the document object to access the element.

  2. The variable comments is an array, and you are trying to access the text property from it when there is no text property on comments.

  3. Make sure to pass the current input value to the function so that you can set the text of the newly created LI with the appropriate value.

  4. Instead of using map(), consider using push() to add an item to the array. Also, note that nextId is a variable and should not have quotes around it when used as such.

  5. To enhance user experience, I recommend clearing the input value after creating the item.

Demo:

let nextId = 1;

const comments = [];

const commentForm = document.querySelector('[data-id="comment-form"]');
const commentInput = commentForm.querySelector('[data-input="comment"]');
const button = commentForm.querySelector('[data-action="add"]');
const commentList = document.querySelector('[data-id="comment-list"]');
button.addEventListener('click', () => {
  const object = {};
  if (commentInput.value != '') {
    comments.push({ id: nextId++, text: commentInput.value });
  }
  createElement(commentInput.value);
  commentInput.value = '';
});

function createElement(ci) {
  const newComment = document.createElement('li');
  newComment.setAttribute('data-comment-id', comments.id);
  newComment.textContent = ci;
  commentList.appendChild(newComment);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
    <link rel="stylesheet" href="./css/styles.css" />
  </head>
  <body>
    <div id="root">
      <form data-id="comment-form">
        <textarea data-input="comment"></textarea>
        <button type="button" data-action="add">Add</button>
      </form>
      <ul data-id="comment-list"></ul>
    </div>
    <script src="./js/app.js"></script>
  </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate multiple Bootstrap templates into an Angular project without causing conflicts between them?

When incorporating a bootstrap template into the admin interface, it is important to consider that its design may vary from the template used for visitors. Mixing multiple styles based on different templates can lead to conflicting styles and can potenti ...

ng serve issue persists even after resolving vulnerabilities

Can anyone assist me in resolving why I am unable to start my project after fixing 3 high vulnerabilities? I ran npm audit to identify the vulnerabilities and then used npm install --save-dev @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

What are the best scenarios for utilizing (a)synchronous calls?

Currently, I am working on a project for my office as a learning exercise. We have a tradition of bringing food every Monday, so I decided to create a program that displays each person's turn. My webpage can generate a calendar with a spare color colu ...

Automatically refreshing Ajax causes the div to disappear after a designated amount of time

Having an issue where I'm trying to refresh the content of my <div> every 5 seconds. Strangely, it was working fine a few days ago and I haven't made any changes to the code since then. However, after 5 seconds, the <div> disappears ...

What is the best way to effectively adjust the code structure in a Node.JS project?

[Summarized] Focus on the bold parts. Although I am relatively new to Node.JS, I have been able to successfully build some projects. However, I have come across a burning question that has left me frustrated after searching Google for answers without much ...

Challenges with loading content on the initial page load using the HTML5

Upon page load, I wanted to save the initial page information so that I could access it when navigating back from subsequent pages. (Initial Page -> Page2 -> Initial Page) After some trial and error, I ended up storing a global variable named first ...

Is it possible in Vue.js to create a reactive functionality for a button using a watcher for "v-if" condition?

I have a userlist page with various profiles, including my own. A button is supposed to appear only when viewing my own profile. The issue arises when switching from a different profile to my own (changing the router parameter) - the button should show up ...

How can one ensure the preservation of array values in React?

I'm struggling to mount a dynamic 'select' component in React due to an issue I encountered. Currently, I am using a 'for' loop to make API calls, but each iteration causes me to lose the previous values stored in the state. Is t ...

Scrolling text box utilizing Jquery

Currently, I am utilizing a scrolling box that functions well * view here * under normal circumstances. However, when there is an extensive amount of content below it, such as: <article class="content"> ...

Seamless Integration of jQuery Functions

I am in need of some assistance with passing a chain of jQuery methods into a function as an argument. The goal is to have dynamic methods executed on a DOM object. This functionality would be particularly useful for writing qUnit tests where centralizat ...

Validate Wildcard Array of Objects with Express-Validator version 5.2.0 - A Comparison Guide

Struggling to validate an array of objects using express-validator. Utilizing the "wildcard" and "custom", I'm looping through the objects in the array to compare keys. The issue arises with an object structured like this: flavors:[ { name: &apos ...

Guide to modifying the value of a JSON attribute in JavaScript

Here's a snippet from my json file: { "@id": "2", "@samsid": "d7058536c89b46c0b58117eff64372f7", "@productname": "Another paid for", "@downloaddate": "2013-05-28 11:37:12Z", "@downloadlocation": "2AFoGZVJpFHzspQD9UoE2C4VFYc8idiO4ebaRx4uEvtG+ ...

Passing a JSONArray to a webview using addJavascriptInterface can provide valuable data

Within my Android app assets, I have stored an HTML page that I want to display using a WebView and add parameters to the webpage. To achieve this, I populated all the values in a JSONArray and utilized 'addJavascriptInterface' to incorporate th ...

jQuery unable to find designated elements in uploaded templates

I have a specific route linked to a specific controller and view: app.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/create', { templateUrl: 'partials/form/form.html', controlle ...

Conceal the "Load More" button on the filter tabs, with the exception of the "

My website features filterable tabs and photos categorized into different groups. The main category is "All" followed by 4 additional categories. There are two important functions that I have implemented: The first function is for filtering: $(function( ...

Attach a Material-UI Popper component to a customized edge label in a React Flow

After finding inspiration from this particular example in the react-flow documentation, I decided to create my own customized version. It showcases a Material Ui Popper that appears when the edge is selected. However, my problem arises when attempting to z ...

What is the best way to retrieve the data stored in a TD element within a TR row in an HTML table?

How can I retrieve the value of a clicked table cell? https://i.stack.imgur.com/HfXBK.png <table id="table" class="table" style="margin-right: auto; margin-left: auto" > <thead> <tr> <th>Request Number</th> ...

How to Send a Multi-part Message Using AT Commands and PDU Mode in Node.js

I am trying to send a multipart message using AT commands. Single parts work fine, as do special characters. However, when the message exceeds 160 characters, it shows as sent but nothing is received. const async sendSMS(msisdn, message) { message += ...

React state not refreshing as expected due to hook issues

I am in the process of creating a small memory game using React as a learning exercise. The main concept is to click on a tile, have it shuffled, and then try to select one that you haven't clicked before. However, I am encountering difficulties in up ...

Tsyringe - Utilizing Dependency Injection with Multiple Constructors

Hey there, how's everyone doing today? I'm venturing into something new and different, stepping slightly away from the usual concept but aiming to accomplish my goal in a more refined manner. Currently, I am utilizing a repository pattern and l ...