0

I'm trying to create a todo app using JavaScript. It creates the li element with the input but it disappears after a second. Can someone tell me what's wrong with my code?

let ul = document.getElementById("ul"); //get the main list. capture ul element
let addBtn = document.getElementById("add-btn"); //button
let todoInput = document.getElementById("todo-input"); //targets the input

addBtn.addEventListener("click", function() {
  let list = document.createElement("li");
  list.innerHTML = todoInput.value;
  ul.appendChild(list);
});
<form>
  <h2>Input todo</h2>
  <input type="text" class="todo" id="todo-input" placeholder="Type your task to add" />
  <button class="btn" id="add-btn" type="submit">Add</button>
</form>
<div class="todo-container">
  <h2>Things to do:</h3>
    <ul id="ul">
    </ul>
</div>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
toytu
  • 21
  • 4

1 Answers1

0

Do it this way

addBtn.addEventListener("click", function(e) {
  e.preventDefault(); // prevent the default behavior (refresh)
  let list = document.createElement("li");
  list.innerHTML = todoInput.value;
  ul.appendChild(list);
});

The page is being submitted, you need to prevent that submit so that the page doesn't refresh.

Abdel
  • 404
  • 2
  • 8