Javascript - get information from the form and display it

Link here:

Hello everyone,

My function getFormData has a forEach inside that is displaying ‘allComments’ array of objects.

When I click submit I want to add name, email and comment to ‘allComments’ and then display it on the HTML like it’s already happening using the forEach.

I would suggest you look at the console in your browser’s dev tools. There may be an error message you might be interested in:

“Uncaught ReferenceError: can’t access lexical declaration ‘allComments’ before initialization”

I have sorted that out but forgot to save, it’s working on my VS Code but still not as I want it exactly because it’s not displaying the new comments, only the existing ones from the array.

Where are you adding the new data to the page?

allComments.forEach(user => {
let commentP = document.createElement(‘p’);
commentP.innerText = Name: ${} Email: ${} Comment: ${user.comment};

this is how I am updating it but once I click submit it’s keeping the previous ‘user, email and comment’ and adding the last one to them so I have duplicates.

If you do a console log on allComments after you push the new info to it you will see that you do not have duplicates in that array. So the duplicate issue is not in the array.

Once you print something to the DOM it stays there until you delete it. So do you think you can figure out why you are getting duplicates on the page?

You have at a few choices to avoid displaying what appears as duplicates. My recommendations are you either:

  1. Only append the latest comment to the DOM (while still pushing the latest comment to the allComments array.
  2. After pushing the new comment to the allComments array, you would iterate through all the comments dynamically creating an html string and after iterating, assign this html string to the innerHTML property of an element containing the comments.
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.