JS:如果select是默认值,则禁用复选框

JS: Make checkboxes disabled if select is default value?

本文关键字:复选框 默认值 如果 select JS      更新时间:2023-09-26

我有一组来自的复选框

<input type="checkbox" name="parts_hoses" id="parts-cb1" value="1">

通过id="parts-cb6"

我有一个#send-product 的选择框

                            <select name="send_product" id="send-product">
                                <option value="wall-mounted" selected>Wall-mounted (Default)</option>
                                <option value="freestanding">Freestanding</option>
                                <option value="third_party">Third Party</option>
                            </select>

当它处于默认值"壁挂式"时,复选框会被启用(默认情况下是这样),但当我将其切换到列表中的另一个选项时。。。我想禁用复选框。

这是我目前为止的JS(不起作用):

  function switchProduct() {
    var checkBoxes = document.querySelectorAll('input[type="checkbox"][id^="parts-cb"]');
    var selectBox = document.getElementById('send-product');
    if (selectBox.value == 'wall-mounted') {
      checkBoxes.disabled = false;
    } else {
      checkBoxes.disabled = true;
    }
  }
  document.getElementById('send-product').addEventListener('change', switchProduct);

我做错了什么?感谢您的帮助!

这是一把小提琴:https://jsfiddle.net/cwkgsuq1/

您缺少循环checkboxes数组集合

普通JS不是jQuery,因此"checkBoxes.disabled = false;"将不起作用
改为

for(var i=0; i<checkBoxes.length; i++) {
    checkBoxes[i].disabled = false;
}

因此,简化后的代码可能看起来像:

function switchProduct() {
  var checkBoxes = document.querySelectorAll('input[type="checkbox"][id^="parts-cb"]');
  var selectBox = document.getElementById('send-product');
  for(var i=0; i<checkBoxes.length; i++) {
    checkBoxes[i].disabled = selectBox.value == 'wall-mounted';
  }
}
document.getElementById('send-product').addEventListener('change', switchProduct);
switchProduct();
<select name="send_product" id="send-product">
  <option value="wall-mounted" selected>Wall-mounted (Default)</option>
  <option value="freestanding">Freestanding</option>
  <option value="third_party">Third Party</option>
</select><br><br>
<input type="checkbox" id="parts-cb1" value="1">
<br>
<input type="checkbox" id="parts-cb2" value="1">
<br>
<input type="checkbox" id="parts-cb3" value="1">