简体   繁体   English

如何将事件侦听器添加到动态创建的复选框,以及如何检查复选框是否已选中。 JavaScript的

[英]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. 我想向事件<li>创建的复选框添加事件侦听器。触发事件后,我想检查事件是选中还是未选中。根据我的理解,复选框的事件是“ onChange”,属性是“已检查”,但我的解决方案无法正常工作。

Can someone please explain to me why this solution does not work? 有人可以向我解释为什么该解决方案不起作用吗? New to JavaScript so please explain in the most simple way. JavaScript的新手,因此请以最简单的方式进行说明。 JavaScript only please Thank you in advance 仅JavaScript,请先谢谢

HTML 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 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;' 您可以将事件处理程序绑定到动态创建的元素,就像为它们分配ID一样,例如通过执行'li.onclick = checkCount;' , where checkCount is the name of the function you want to assign to the handler. ,其中checkCount是您要分配给处理程序的函数的名称。 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. 经过大量的时间和精力,我创建了一个函数来检查复选框的状态,将检查的数字推入数组,然后返回span标记内数组的长度(也就是动态单击的复选框)。

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. 将事件侦听器添加到复选框时,重要的是要声明其他函数为false,否则绑定将无法工作。 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) . 它不起作用,因为在添加事件侦听器时该复选框不存在: 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";
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用于检查是否在动态创建的按钮单击时选中了动态创建的复选框的Javascript - Javascript to check if a dynamically created checkbox is checked on a dynamically created button click 如何检查使用jQuery Mobile在JavaScript中动态创建的复选框事件 - how to check checkbox event dynamically created in javascript using jquery mobile 我使用php创建了一个动态复选框,但是当我使用.checked()进行检查时,仅选中了第一个单选按钮。 如何检查其余部分? - I have created a dynamic checkbox using php, but when i use .checked() to check it, only first radio button is checked. how to check the rest? 如何检查是否在Javascript中选中了复选框 - How to check if checkbox is checked in Javascript 如何检查是否在javascript中选中了复选框? - How to check if a checkbox is checked in javascript? 如何使 JavaScript 事件侦听器检测动态添加的复选框事件 - How to make JavaScript event listener detect dynamically added checkbox events 需要在选中复选框后立即取消选中它。 角度4 - need to un-check a checkbox as soon as it is checked. Angular 4 复选框 检查事件侦听器 - Checkbox Check Event Listener 如何在数组中存储动态创建的选中复选框? - how to store dynamically created checked checkbox in array? 面板上的toggleDown仅选中复选框。 Javascript / jQuery - Panel toggleDown only the checkbox checked. Javascript/jQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM