简体   繁体   中英

How do you append user input to an existing document through JavaScript?

I'm trying to create a to-do list and this code allows the user's "to-do" to be printed on the webpage, but it disappears when you stop clicking enter. Does anyone know what I'm doing wrong?

const addButton = document.querySelector(".button");
const inPut = document.querySelector(".inPut");
const space = document.querySelector(".toDo");

addButton.addEventListener("click", () => {
     const entry = document.createElement("div");
     const item = document.createElement("li");
     item.innerText = inPut.value;
     entry.append(item);
     space.append(entry);
});

I suspect it's because you have your HTML wrapped in a <form tag which is causing a page refresh every time you click the button. There are a couple ways to disable this, one of which is adding onsubmit="return false;" to your form tag:

 const addButton = document.querySelector(".button"); const inPut = document.querySelector(".inPut"); const space = document.querySelector(".toDo"); addButton.addEventListener("click", () => { if (inPut.value.trim() == '') return; const entry = document.createElement("div"); const item = document.createElement("li"); item.innerText = inPut.value; entry.append(item); space.append(entry); inPut.value = "" // clear the input for the next to-do });
 <form onsubmit='return false;'> <div> <input class='inPut' /> </div> <div class='toDo'></div> <button class='button'>add to the list</button> </form>

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