首页 > 解决方案 > 多个复选框动作

问题描述

我想制作多个复选框,每次我检查其中一个复选框时,第一个输入的值都会减少一个数字,例如,当我们选择 checkbox1 时,输入中的数字减少 10,当我们选择 checkbox2 时,它减少 20,当我们选择它们都减少了 30。不过,我已经处理了第一个复选框。

<html lang="en">
<head>
</head>
<body>
    <input type="number" id="input">
    <input type="checkbox" onclick="one()" id="checkboxId">
    <input type="checkbox" onclick="" id="checkboxId2">
    <p id="par">hello</p>
    <script>
        function one () {
            var check = document.getElementById("checkboxId");
        if (check.checked) {
            let input = document.getElementById("input").value;
            y = input - 10;
            document.getElementById("par").innerHTML = y;
        } else {
             document.getElementById("par").innerHTML=document.getElementById("input").value;
            }
        }
    </script>
</body>
</html>

标签: javascripthtml

解决方案


您可以尝试使用data-*属性。此外,您只能从选中的复选框中获取值,将它们相加并从输入值中扣除。

试试下面的方法:

function one () {
  var total = Array.from(document.querySelectorAll(':checked'))
              .map(el => el.getAttribute('data-value'))
              .reduce((a,c) => a+ Number(c), 0);
   document.getElementById("par").textContent = Number(document.getElementById("input").value) - total;
}
<input type="number" id="input">
<input type="checkbox" onclick="one()" data-value="10" id="checkboxId">
<input type="checkbox" onclick="one()" data-value="20" id="checkboxId2">
<p id="par">hello</p>


推荐阅读