0

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);
});
sara
  • 13
  • 2
  • 1
    Your code looks fine. Is something else causing the page to refresh? Take a look at my fiddle, and the button appends todos just fine. https://jsfiddle.net/9zw2qvpj/ – Alan May 28 '21 at 02:24
  • Does this answer your question? [Intercept a form submit in JavaScript and prevent normal submission](https://stackoverflow.com/questions/5384712/intercept-a-form-submit-in-javascript-and-prevent-normal-submission) – dale landry May 28 '21 at 02:57

1 Answers1

0

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>
Kinglish
  • 23,358
  • 3
  • 22
  • 43