简体   繁体   中英

JS: Make checkboxes disabled if select is default value?

I have a set of checkboxes from

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

through id="parts-cb6"

I have a select box of #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>

that when it is on its default value, "wall-mounted", the checkboxes are enabled (as they are by default), but when I switch that to another option in the list... I'd like to disable the checkboxes.

Here is my JS so far (doesn't work):

  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);

What am I doing wrong? Any help is appreciated!

Here's a fiddle: https://jsfiddle.net/cwkgsuq1/

You're missing to loop your checkboxes Array collection .

plain JS is not jQuery, therefore " checkBoxes.disabled = false; " will not work .
Instead :

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

So your code simplified could look like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM