簡體   English   中英

JS:如果選擇是默認值,則禁用復選框?

[英]JS: Make checkboxes disabled if select is default value?

我有一組復選框

<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 Array collection

純 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">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM