I'm trying to create a TODO list in javascript but I encounter the following problem when trying to implement a remove task function. The addTodo()
function adds a new <div>
with a checkbox, a label, and a button for deleting the task. This button is supposed to call the function removeTodo(button)
, which deletes the parent div when called but nothing happened and the button addTODO gets associated with that remove function too even if it's not supposed to be.
The expected behavior is that when the X button is clicked, the parent div of that button is deleted.
Here is the code:
var counter = 1;
function addTODO() {
var new_div = document.createElement('div');
var new_checkBox = document.createElement('input');
new_checkBox.type = "checkbox";
new_checkBox.id = "chk" + counter;
var new_label = document.createElement('label');
new_label.for = new_checkBox.id;
new_label.innerHTML = document.getElementById('text_input').value;
var new_button = document.createElement('button');
new_button.addEventListener('click', removeTodo(this));
new_button.innerHTML = "X";
new_div.appendChild(new_checkBox);
new_div.appendChild(new_label);
new_div.appendChild(new_button);
document.getElementById('todoBlock').appendChild(new_div);
counter++;
new_button.addEventListener('click', removeTodo(this));
}
function removeTodo(button) {
button.parentNode.remove();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TODO List</title>
</head>
<body>
<h1> My TODO List </h1>
<!-- premier bloc de TODO -->
<div id="todoBlock">
<div>
<input type="checkbox" id="chk1">
<label>First Todo</label>
<button onclick="removeTodo(this)">X</button>
</div>
</div>
<button id="todoAdder" onclick="addTODO()">add Todo</button>
<input type="text" id="text_input" placeholder="Entrez votre tâche">
<script type="text/javascript" src="Main.js"></script>
</body>
</html>