简体   繁体   中英

Why does my onclick property not run the function upon submit?

everyone. Bit of a JS noob. First question on here. I tried being more specific through the Stack Overflow submission guidelines but I'm not sure how to, as I'm not sure what's wrong with this. Tips to become a better asker are appreciated.

I'm building a simple JS todo list, trying not to use video tutorials. I just simply can't figure out what's wrong with this. On hitting the 'submit' button, nothing happens either in the console log or on the actual page. What am I doing wrong?

 let todoInput = document.getElementById("input"); let list = document.getElementById("submit"); let form = document.getElementById("form"); list.onclick = function addTodo(e) { e.preventDefault(); // todo div const todoDiv = document.createElement('div'); todoDiv.classList.add('todo'); // todo LI const newTodo = document.createElement('li'); newTodo.innerText = todoInput.value; newTodo.classList.add('todo-item'); todoDiv.appendChild(newTodo); if (todoInput.value === "") { return null } };
 <h1>TODO LIST</h1> <form id="form" onload="false"> <input id="input" type="text"> <input id="submit" type="submit" value="Submit"> </form> <div id="output"></div>

That's because when you've created the todoDiv element, you are not appending it to your DOM at all. If you want to append it to the #output element, you can add the following line at the very end:

document.getElementById('output').appendChild(todoDiv);

NOTE: Your li elements must be appended to <ul> elements. You can just change #output to be a <ul> element and append your list items directly to it:

See proof-of-concept below:

 let todoInput = document.getElementById("input"); let list = document.getElementById("submit"); let form = document.getElementById("form"); let output = document.getElementById("output"); list.onclick = function addTodo(e) { e.preventDefault(); // todo LI const newTodo = document.createElement('li'); newTodo.innerText = todoInput.value; newTodo.classList.add('todo-item'); output.appendChild(newTodo); };
 <h1>TODO LIST</h1> <form id="form" onload="false"> <input id="input" type="text"> <input id="submit" type="submit" value="Submit"> </form> <ul id="output" class="todo"></ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM