javascript - 在 js 中总结并检查了 2 个选项

标签 javascript html checkbox

我在 html 中有这段代码

<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">

<p id="total"></p>

然后是js

var total = 0;

function calculate(option) {
    if (option.checked) {
        total += Number(option.value);
    } else {
        total -= Number(option.value);
    }
    document.getElementById("total").innerHTML = total;
}

我需要前两个检查复选框来总结页面加载时的情况 在 js 的行为之后,分别检查和取消选中时使我达到 0 或复选框总数

最佳答案

您可以向页面加载添加一个事件监听器,然后只需使用 querySelectorAll("input[type=checkbox]") 选择选项即可选择所有复选框,对它们进行迭代并对它们进行求和。

var total = 0;

function calculate(option) {
  if (option.checked) {
    total += Number(option.value);
  } else {
    total -= Number(option.value);
  }
  document.getElementById("total").innerHTML = total;
}

window.addEventListener("load", function() {
  var options = document.querySelectorAll("input[type=checkbox]");
  for (var i = 0; i < options.length; i++) {
    const o = options[i];
    if (o.checked) total += Number(o.value);
  }
  document.getElementById("total").innerHTML = total;
}, false);
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">

<p id="total"></p>

关于javascript - 在 js 中总结并检查了 2 个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49710355/

相关文章:

javascript - fetch() 完成后如何调用函数

javascript - 将 lodash _.uniqBy() 转换为原生 javascript

javascript - 使用 requestAnimationFrame 异步加载 CSS 样式表

javascript - 当我返回 angularJS 中的 ui-view 时,复选框未选中

Javascript 计算选中的复选框而不计算另一个复选框

javascript - jQuery 中的循环复选框列表以匹配重复的类

javascript - 如何在 Firefox 中保持通知打开状态?

javascript - 如何在单击图像时刷新特定的 div

javascript - 如何防止搜索框崩溃?

html - Firefox 缓存隐藏的输入