简体   繁体   中英

How to add event listener to a dynamically created checkbox and check if checkbox is checked. JavaScript

I want to add an event listener to the checkbox that is created within an <li> When the event is triggered I want to check if it is checked or unchecked From my understanding the event for a checkbox is "onChange" and the property is "checked" but my solution is not working.

Can someone please explain to me why this solution does not work? New to JavaScript so please explain in the most simple way. JavaScript only please Thank you in advance

HTML

 <body>
    <div class="wrapper">
        <ul id="taskList">

        </ul>
        <div id="add-task-area">
            <input type="text" id="addTaskInput" value="">
            <button id="addTaskButton">Add Task</button>
        </div>
    </div>
</body> 

JAVASCRIPT

let taskList = document.querySelector("#taskList");
const addTaskInput = document.querySelector("#addTaskInput");
const addTaskButton = document.querySelector("#addTaskButton");

const addTask = () => {
        if (addTaskInput.value != " ") {
            let taskItem = document.createElement("li");    
            let taskText = document.createElement("span");
            taskText.textContent = addTaskInput.value;
            let checkBox = document.createElement("input");
            checkBox.setAttribute("type", "checkBox");
            checkBox.setAttribute("class", "checkbox");
            let removeItem = document.createElement("button");
            removeItem.setAttribute("class", "remove");
            removeItem.textContent = "Delete";
            taskList.appendChild(taskItem);
            taskItem.appendChild(taskText);
            taskItem.appendChild(checkBox);
            taskItem.appendChild(removeItem);
            addTaskInput.value = " ";
        };
}

addTaskButton.addEventListener("click", addTask);

addTaskInput.addEventListener("keydown", (event) => {
    if (event.keyCode == 13) {
   addTask();
  }});

let checkbox = document.querySelectorAll(".checkbox")
checkbox.addEventListener("onChange", test);

const test = () => {
if (checkbox.checked) {
alert("checked");
} else {
  alert ("unchecked")
}
}

I am working on the same problem and managed to get it figured out! You can bind event handlers to dynamically created elements the same way you assign an id to them, such as by doing 'li.onclick = checkCount;' , where checkCount is the name of the function you want to assign to the handler. After a lot of time and effort, I created a function that checks the state of checkboxes, pushes the number that are checked to an array, and returns the length of the array(aka the dynamically clicked checkboxes) within a span tag.

When you add the event listener to the checkbox, it is important to state that the other function is false, or else the binding will not work. I have attached my code below, I hope it is helpful to you.

    const list = document.getElementById("todo-list");

    //creates new li and checkboxes
    function newTodo(evt) {
    //stops page from reloading every time
      evt.preventDefault();
      const input = document.getElementById("todo-text").value;
      const li = document.createElement("li");
      li.appendChild(document.createTextNode("- " + input));
      list.appendChild(li);
      document.getElementById("todo-text").value = "";
      var checkbox = document.createElement('input');
      checkbox.type= "checkbox";
      checkbox.value = 1;
      checkbox.class = "todo";
      li.appendChild(checkbox);
      li.onclick = checkCount;

    }
// binds event listener to call first function

    const form = document.getElementById("btn").addEventListener('click', newTodo);

//specifies this will call only 2nd function since 1st function has finished

    check = document.getElementsByClassName('todo');
    for (var i = 0; i < check.length; i++) {
        check[i].addEventListener('click', newTodo, false);
    }



    const checkCount = function () {
        var selected = [];
        var span = document.getElementById('item-count');
        var checkboxes = document.querySelectorAll('input[type=checkbox]:checked');
        for (var i = 0; i < checkboxes.length; i++) {
            selected.push(checkboxes[i]);

            }
            span.innerHTML = selected.length;


    };

It doesn't work because the checkbox doesn't exist by the time you are adding the event listener: checkbox.addEventListener("onChange", test) .

You can try adding the event listener right after you create the checkbox:

...
var checkbox = document.createElement('input');
checkbox.addEventListener("onChange", test) // <-- add this line
checkbox.type= "checkbox";
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM