###目的
自動でチェックする機能をかなり頑張って作ったのですが、親要素の取得で躓いています。上手な取得方法を知りたいです。
###現状と問題
子チェックしたときに、「.parents」(←sがついてる)を使っているせいで、自分の親だけでなく別の親のチェックボックスも拾ってチェックを入れてしまうのです。
下記コードで言うと、「親apple」の「子1・2」にチェックを入れると、.paretnsのせいで「別の親grape」にまでチェックが入ってしまいます。
どなたか、上手な方法をご教示頂けませんでしょうか?
▼動くサンプル
https://jsfiddle.net/79cqw3fh/
▼そのコード
html
1<ul class="c-checklist"> 2 <li><input id="c-apple" type="checkbox" name="chk_fluits2"> 3 <label for="c-apple" class="check_label_c"> 4 <p>apple</p> 5 <ul> 6 <li><input id="c-apple-1" class="check-c check-1" type="checkbox" name="chk_fluits" value="c-apple-1" target="c-apple-1"><label for="c-apple-1" class="check_label_1">1</label></li> 7 <li><input id="c-apple-2" class="check-c check-2" type="checkbox" name="chk_fluits" value="c-apple-2" target="c-apple-2"><label for="c-apple-2" class="check_label_2">2</label></li> 8 </ul> 9 </label> 10 </li> 11 <li><input id="c-grape" type="checkbox" name="chk_fluits2"> 12 <label for="c-grape" class="check_label_c"> 13 <p>grape</p> 14 <ul> 15 <li><input id="c-grape-1" class="check-c check-1" type="checkbox" name="chk_fluits" value="c-grape-1" target="c-grape-1"><label for="c-grape-1" class="check_label_1">1</label></li> 16 <li><input id="c-grape-2" class="check-c check-2" type="checkbox" name="chk_fluits" value="c-grape-2" target="c-grape-2"><label for="c-grape-2" class="check_label_2">2</label></li> 17 </ul> 18 </label> 19 </li> 20</ul>
javascript
1////親チェックしたとき 2//子を2つともチェックする。または子が2つチェックされていたら外す。 3(function($){ 4$('input[name="chk_fluits2"]').change(function(){ 5 6 var childfluits = $(this).parent().find('input[name="chk_fluits"]'); 7 var checkcount = $('.check-c:checked').length; 8 9 if (checkcount == 2 ){ 10 $(childfluits).prop('checked', false); 11 $(this).prop('checked', false); 12 } else { 13 14 if ($(this).prop("checked") == true) { 15 $(childfluits).prop('checked', true); 16 } else { 17 $(childfluits).prop('checked', false); 18 } 19 } 20 21}); 22})(jQuery); 23 24 25////子チェックしたとき 26//2つともチェックが入ったら、親チェックも入れる 27(function($){ 28$('input[name="chk_fluits"]').change(function(){ 29 30 var parentfluits = $(this).parents().find('input[name="chk_fluits2"]'); 31 var checkcount = $('.check-c:checked').length; 32 33 if (checkcount == 2 ){ 34 $(parentfluits).prop('checked', true); 35 } 36 37}); 38})(jQuery); 39 40 41////子チェックしたとき 42//2つともチェックが外されたら、親チェックも外す 43(function($){ 44$('input[name="chk_fluits"]').change(function(){ 45 46 var parentfluits = $(this).parents().find('input[name="chk_fluits2"]'); 47 var checkcount = $('.check-c:checked').length; 48 49 if (checkcount == 0 ){ 50 $(parentfluits).prop('checked', false); 51 } 52 53}); 54})(jQuery);
あとできれば、上の冗長であろうjQueryを、もっとスマートにもしたいのですが、どのような考え方をすればいいかお導き頂けると嬉しいです。
よろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー