javascript - 如果单击多个复选框中的一个复选框,如何触发函数

标签 javascript checkbox

我正在创建一个 Todo 应用程序,当选中任何一个复选框时,我需要触发一个函数(计算选中的复选框的数量)。

如果单击复选框,我无法发生 onlick 事件。我已经设法使用提交按钮来做到这一点,但不能使用复选框本身来做到这一点

//the html
<div class="flow-right controls">
        <span>Item count: <span id="item-count">0</span></span>
        <span>Unchecked count: <span id="unchecked-count">0</span></span>
      </div>
      <button class="button center" onClick="newTodo()">New TODO</button>
      <ul id="todo-list" class="todo-list"></ul>
    </div>

// the function above this one creates the checkbox and appends it to the list in the HTML
const box = document.createElement('INPUT');
      box.type = "checkbox";
      box.name = "countme";
      box.id = "checkme"
      li.appendChild(box);

// this is the code I have created to trigger a function unchecked which returns the count of unchecked checkboxes.

let getcheck = document.getElementsByName("countme");
for (let i = 0; i < getcheck.length; i++) {
   getcheck[i].onClick = unchecked;
 }

没有发生任何事情,所以我不确定如何调试它

最佳答案

我想你需要这个

function newTodo() {
  let ulElement = document.getElementById('todo-list');
  let todoElement = document.createElement('li');
  const box = document.createElement('INPUT');
      box.type = "checkbox";
      box.name = "countme";
      box.id = "checkme";
      box.value = 0;
      todoElement.appendChild(box);
  const span = document.createElement('span').TEXT_NODE = 'To do task';
  todoElement.append(span);
  ulElement.append(todoElement);
  let unCheckELement = document.getElementById('unchecked-count');
  unCheckELement.textContent = parseInt(unCheckELement.textContent) + 1;
  box.onchange = onCheckboxCheck;
}
function onCheckboxCheck(element) {
  let count = parseInt(document.getElementById('item-count').textContent);
  count += element.srcElement.checked ? 1 : -1;
  let allElements = document.querySelectorAll('#todo-list li').length;
  document.getElementById('item-count').textContent = count;
  document.getElementById('unchecked-count').textContent = allElements - count;

}
<div class="flow-right controls">
    <span>Item count: <span id="item-count">0</span></span>
    <span>Unchecked count: <span id="unchecked-count">0</span></span>
  </div>
    <button class="button center" onClick="newTodo()">New TODO</button>
    <ul id="todo-list" class="todo-list"></ul>

关于javascript - 如果单击多个复选框中的一个复选框,如何触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57257006/

相关文章:

javascript - 我如何在 jQuery 插件中返回一个子集?

javascript - 从 highcharts 图表中删除所有系列数据的正确方法?

javascript - Node.js:如何访问使用 node-imap 收到的电子邮件的 “To” 、 “Body” 和 “From” 字段?

css - ionic 复选框 :checked not working angular 2 ionic 2

javascript - 简化 JavaScript 代码

javascript 需要从复选框数组中选中一个复选框

javascript - 单击文件上传按钮后出现延迟?

javascript - 使用 lodash 比较两个对象数组并返回一个具有共同值的数组

jquery - 如果 jquery 中未选中复选框,则禁用提交按钮

python - 如何在Python中创建一个按钮来保存复选按钮的状态?