skip to Main Content

I want to create a todo list using array and loop and display the list in div container. I am able to display the list but it is muliplying the same list stored and is displayed.

<body>
    <p class="title"> Todo List </p>
    <input type="text" class="js-input-todo" placeholder="Todo name">
    <button type="submit" class="js-btn-todo" onclick="handleAddTodo()">Add</button>

    <div class="todo-list"></div>

 <script src="script/11-arrays-loop.js"></script>
</body>

//script 

let names = []

let todoListHTML = ''

function handleAddTodo(){
  const todo_input = document.querySelector('.js-input-todo');
  const todoValue = todo_input.value
  const result = document.querySelector('.todo-list');
 
  names.push(todoValue);
  for(let i = 0; i <  names.length ; i++){
   let todoName = names[i]
   const html = `<p>${todoName} </p>`
   todoListHTML = html;
   result.innerHTML +=todoListHTML;
   
   todo_input.value = '';
  }
  
  

}

I want to the array value to not repeat and displayed in the output

2

Answers


  1. Try This

    <!DOCTYPE html>
    <html lang="en">
    <head>
    </head>
        <script>
            let names = [];
            let todoListHTML = ''
    
    function handleAddTodo(){
      const todo_input = document.querySelector('.js-input-todo').value;
      const todoValue = todo_input.value
      const result = document.querySelector('.todo-list');
     
      names.push(todoValue); 
       const html = `<p>${todo_input} </p>`
       todoListHTML = html;
      result.innerHTML +=todoListHTML;
      todo_input.value = '';
    }
    </script>
    
    <body>
        <p class="title"> Todo List </p>
        <input type="text" class="js-input-todo" placeholder="Todo name">
        <button type="submit" class="js-btn-todo" onclick="handleAddTodo()">Add</button>
    
        <div class="todo-list"></div>
    
     </body>
    </html>
    
    
    Login or Signup to reply.
  2.     const names = [];
        const result = document.querySelector(".todo-list");
        const todo_input = document.querySelector(".js-input-todo");
        function handleAddTodo() {
          const todoValue = todo_input.value;
          const html = document.createElement("p");
          html.innerHTML = todoValue;
          result.append(html);
          names.push(todoValue);
          todo_input.value = "";
          console.log(names, "names");
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search