JavaScript DOM Scripting By Example Adding and Removing Names Registering Names

Siddharth Pandey
Siddharth Pandey
3,449 Points

Why doesn't my code work?

I was following along with the video(name of video is shown uptop), and my code is not registering anything to the document(a new list item with the name of the person typed is not being added) why is it not working? Furthermore no syntax errors are shown in the console, please help.

Here is my code:

const form = document.querySelector('#registrar');
const input = form.querySelector('input');


input.addEventListener('submit', function submit(name) {
  name.preventDefault();
  let text = input.value;
  const ul = document.querySelector('#invitedList');
  let li = document.createElement('li');
  li.textContent = text;
  ul.appendChild(li);
});

2 Answers

The event listener should be called on the form not the input. This should fix your problem and get everything working, but you don't need to name the function passed in to the listener since it should be anonymous and the argument should be called event or e since that is what you will be using in the function.

const form = document.querySelector('#registrar');
const input = form.querySelector('input');


form.addEventListener('submit', function(event) {
    event.preventDefault();
    let li = document.createElement('li');
    li.textContent = input.value;
    document.querySelector('#invitedList').appendChild(li);
});
Siddharth Pandey
Siddharth Pandey
3,449 Points

Thanks so much :-), that got it working!

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 47,493 Points

Why did you deviate so much from the provided code? To start with see the following from MDN where you find:

Note that the submit event fires on the <form> element itself, and not on any <button> or <input type="submit"> inside it. (Forms are submitted, not buttons.)

Siddharth Pandey
Siddharth Pandey
3,449 Points

I deviated because I wanted to try doing it myself as opposed to just copying the teacher, thanks for the tips btw :-)