如何将两个复选框值相加



假设我有这些复选框:

<head>
<title>Title of the document</title>
</head>
<body>
<ol>
<li><input type="checkbox" id="1" value="1"> 1</p>
<li><input type="checkbox" id="2" value="2"> 2</p>
<li><input type="checkbox" id="3" value="3"> 3</p>
</ol>
<button type="button" class="check">Submit</button>

如何单击"提交"按钮将所选框添加到一起?比如,如果我选中了1和3框,我该如何将它们相加,以便在屏幕上打印4或任何数字组合?

您可以使用:checked选择器来获取所有复选框,然后对所有复选框进行循环以求和它们的值。

document.querySelector('button.check').addEventListener('click', function(e){
const checked = document.querySelectorAll('ol input:checked');
let sum = 0;
checked.forEach(box => sum += +box.value);
console.log(sum);
});
<ol>
<li><input type="checkbox" id="1" value="1"> 1</p>
<li><input type="checkbox" id="2" value="2"> 2</p>
<li><input type="checkbox" id="3" value="3"> 3</p>
</ol>
<button type="button" class="check">Submit</button>

最新更新