Home > Software design >  The event 'onchange' I added to my checkbox doesn't work in JavaScript
The event 'onchange' I added to my checkbox doesn't work in JavaScript

Time:08-19

I'm working on creating a basic ToDo list on web includes adding tasks: represented in structure - and deleting tasks, once the task is 'checked

<!DOCTYPE html>
<html>
<head>
    <title>TheToDoList</title>
</head>

<script>
let counter = 0
let tasks = []

function removeTask(){
    console.log(counter)
}

function addTask(){
    var task = document.getElementById("tsk").value;
    var div = document.getElementById("tsklst");
    var input = document.createElement("input")
    input.type = "checkbox";
    input.id = counter;
    input.value = task;
    input.onchange = removeTask;
    var lable = document.createElement("lable");
    lable.innerText = task;
    lable.for = counter;
    div.appendChild(input);
    div.appendChild(lable);
    div.innerHTML  = '</br>'
    tasks.push(document.getElementById(counter))
    counter  ;
}
</script>

<body>
<h1>My ToDo List</h1>
<input id="tsk" type="text" placeholder="What You Need To Do?">
<input type="button" value="Add Task" onclick="addTask()">
<div id="tsklst"></div>
</body>
</html>

once a user click on "add task" button the addTask function creates the checkbox with lable contains to task that was written.

the problem is that although i define the onchange event of every checkbox i create, when i check it through the browser - the removeTask function does not respond for some reason.

i put a console.log within the removeTask function, with a counter of the tasks to exemine the situation. - still can't figure it out what is the problem.

CodePudding user response:

Comment your code and set the change event using setAttribute

// input.onchange = 'removeTask()';
input.setAttribute('onChange', 'removeTask()');

Hope this will work for you. You can inspect that the event attached to your checkbox element

CodePudding user response:

Your current code does not work with this line:

 input.onchange = removeTask;

You need to change it to this:

 input.setAttribute('onChange', removeTask());

The other answer looks correct, but that version of the code did not work for me in JSFiddle. This one does work, I am sure it will fix the issue for you.

Code test in JSFiddle: https://jsfiddle.net/tb68ay9z/1/

CodePudding user response:

When you use innerHTML the HTML is kept but the reference to the events is lost. You should use another way to add that <br> like createElement/appendChild.

// div.innerHTML  = '</br>'
var br = document.createElement("br")
div.appendChild(br);
  • Related