Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSiddharth Pandey
7,280 PointsWhy 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);
});
3 Answers
scribbles
21,173 PointsThe 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);
});
KRIS NIKOLAISEN
54,971 PointsWhy 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
7,280 PointsI deviated because I wanted to try doing it myself as opposed to just copying the teacher, thanks for the tips btw :-)
Mariia Ashurova
10,913 Pointsconst form = document.getElementById('registrar'); const input = form.querySelector('input');
form.addEventListener('submit', (e) => { e.preventDefault(); const text = inpu.value; const ul = document.getElementById('invitedList'); const li = document.createElement('li'); li.textContent = text; ul.appendChild(li); });
It doesn't work! Why?
Siddharth Pandey
7,280 PointsSiddharth Pandey
7,280 PointsThanks so much :-), that got it working!