前提・実現したいこと
javascript、jQueryを独学で学んでいます。
ラジオボタン(チェックボックス)が入れ子の場合に、parentを選択時、そのchildrenのみ選択可能状態に切り替えるjQueryを組んでいます。
parentにチェックが入っている場合は、それに付随したchildrenのみラジオボタン(チェックボックス)が選択可能な状態にしたいのですが、
どうしても、parentとそのchildrenというのが指定できず、全てのchildrenボタンが切り替わってしまいます。また、元に戻りません。
希望の仕様はこれです。
初期値は、全てのchildrenは選択不可状態
single選択時は全てのchildrenはチェックを外し、選択不可状態
parent選択時は、付随するchildrenのみ選択可能状態にし、他のchildrenはチェックを外し、選択不可状態にする
parentの選択が外れたら、そのchildrenはチェックを外し、選択不可状態にする
行き詰まっています。よろしくお願いします。
HTML
<ul> <li><label><input type="radio" name="item" id="single">single</label></li> <li><label><input type="radio" name="item" id="parent">parentA</label> <ul> <li><label><input type="radio" name="children">children</label></li> <li><label><input type="radio" name="children">children</label></li> </ul> </li> <li><label><input type="radio" name="item" id="parent">parentB</label> <ul> <li><label><input type="radio" name="children">children</label></li> <li><label><input type="radio" name="children">children</label></li> </ul> </li> <li><label><input type="checkbox" name="item" id="parent">parentC</label> <ul> <li><label><input type="checkbox" name="children">children</label></li> <li><label><input type="checkbox" name="children">children</label></li> </ul> </li> </ul>
jQuery
$(function(){ $('input[id=parent]').each(function() { //デフォルト $('input[name="children"]').prop('checked', false).prop('disabled', true); $('input[id=parent]').change(function() { //parentがチェックされたら直下のchildrenのみチェック可 if ($(this).prop("checked")) { $('input[name="children"]').prop('checked', true).prop('disabled', false); } else { //parentがチェックされていない直下のchildrenはチェック不可 $('input[name="children"]').prop('checked', false).prop('disabled', true); } }); }); });
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/02/04 13:32