我想创建多个复选框,并且每次选中其中一个时,第一个输入的值都会减少一个数字,例如,当我们选择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>

最佳答案

您可以尝试使用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>

09-17 14:29
查看更多