首页 > 解决方案 > 在 JavaScript 中检查其中一些复选框后禁用剩余的复选框

问题描述

我想在达到选中复选框的限制时禁用复选框。我在 JavaScript 中创建了一个函数,其中在选中两个框时,其他两个框将变为禁用,并且选中框的值位于 id="order2" 中。但是这个功能根本不起作用。

<!DOCTYPE html>
<html>
<body>

<p>How would you like your coffee?</p>

<form name="myform" action="/action_page.php">
<input type="checkbox" name="coffee" onclick="myFunction2()" value="100">With cream<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="150">With sugar<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="200">With milk<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="250">With tea<br>
<br>


<input type="text" id="order2" size="50">
<input type="text" id="order3" size="50">
<input type="submit" value="Submit">
</form>

<script>
function myFunction2() {
  var coffee = document.querySelectorAll("[name = coffee]"); // To get arrays by Attribute in query selector use [] to get arrays of the same attribute. We can also use ("input[type = checkbox]") to get arrays.
  var txt = "";
  var i;
  for (i = 0; i < coffee.length; i++) {
   if (coffee[i].checked) {
      txt = txt + coffee[i].value + ", ";
      document.getElementById("order2").value = "You ordered a coffee with: " + txt.slice(0, -2);
    }

    else if (coffee.length === 2) {
     coffee[i].setAttribute("style", "pointer-events: none; opacity: 0.5");
     document.getElementById("order3").value = "Boxes left uncheck " + i;
    }
  }

}
</script>
</body>
</html>

标签: javascript

解决方案


做两个循环。首先弄清楚被选中的复选框的总数——这将告诉你是否需要禁用未选中的复选框。在第二个循环中,如果选中了复选框,则将其添加value到数组中。否则,复选框未选中;如果至少有 2 个复选框被选中(由上一个循环标识),则禁用它。

如果用户在达到 2 的限制后取消选择一个选项,也循环检查复选框并启用它们。

function myFunction2() {
  const checkboxes = [...document.querySelectorAll("[name = coffee]")];
  const boxesChecked = checkboxes.reduce((a, b) => a + b.checked, 0);
  document.getElementById("order3").value = "Options left to choose:" + (2 - boxesChecked);
  let addedCost = 0;
  for (const checkbox of checkboxes) checkbox.disabled = false;
  for (const checkbox of checkboxes) {
    if (checkbox.checked) addedCost += Number(checkbox.value);
    else if (boxesChecked === 2) checkbox.disabled = true;
  }
  document.getElementById("order2").value = "Costs: " + addedCost;
}
<p>How would you like your coffee?</p>

<form name="myform" action="/action_page.php">
  <input type="checkbox" name="coffee" onclick="myFunction2()" value="100">With cream<br>
  <input type="checkbox" name="coffee" onclick="myFunction2()" value="150">With sugar<br>
  <input type="checkbox" name="coffee" onclick="myFunction2()" value="200">With milk<br>
  <input type="checkbox" name="coffee" onclick="myFunction2()" value="250">With tea<br>
  <br>


  <input type="text" id="order2" size="50">
  <input type="text" id="order3" size="50">
  <input type="submit" value="Submit">
</form>


推荐阅读