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
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>