2016-03-24 35 views
1

私はそれがデフォルト値であるとき、「壁掛け」という#send-productJS:selectがデフォルト値の場合、チェックボックスを無効にしますか?

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

の選択ボックスを持っている

id="parts-cb6"

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

からチェックボックスのセットを持っていますチェックボックスは有効になっています(デフォルトでは有効)が、リストの別のオプションに切り替えると...チェックボックスを無効にしたいと思います。ここで

は(動作しない)これまでのところ、私の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/

答えて

1

あなたが不足しているループにご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">

+0

、.disabled部分は、前平野JSと私のために働いたおかげではなく、公正十分に私はそれをループしなければならないことを気付かなかった! – Matthew

+1

@Matthew :)はい、それを処理する独自のmicro-ala-jQuery-libraryを書かない限りループが必要です...また、あなたが使っている 'if/else'も知っていますが、私がしたようにブーリアンに行く(すべてのステートメントで2回forループを繰り返す必要はありません...)!いいぞ!どういたしまして!どうも –

関連する問題