Hoping that someone can help with this one.

I've got an extensive list of checkboxes with a page that I need to make a bit more intelligent (auto).

All checkboxes on the page share the same 'name' attribute, but they do have sub-groupings.

I'm looking to extend this, so when any checkbox is 'checked' within a group, the 'parent' is checked, and if none of the grouped (within the <ul></ul>) then the parent is unchecked.

I've setup a jsFiddle here: http://jsfiddle.net/swdmedia/xsDgm/13/

jQuery

$('input.checkbox').click(function() {
  var parent = $(this).attr('data-parent');

  $('#'+parent).attr('checked', true);
});

HTML

<h4>Agriculture <input type="checkbox" id="cat4" name="cntnt01cd_categories[]" value="4" /></h4>

<ul>
  <li>
    <label for="cat44" class="checkbox">
    <input type="checkbox" class="checkbox" id="cat44" name="cntnt01cd_categories[]" value="44" data-parent="cat4" />Farm Services</label>
</li>
  <li>
    <label for="cat40" class="checkbox">
    <input type="checkbox" class="checkbox" id="cat40" name="cntnt01cd_categories[]" value="40" data-parent="cat4" />Farming</label>
</li>
</ul>

<h4>Automotive Sales and Supplies <input type="checkbox" id="cat5" name="cntnt01cd_categories[]" value="5" /></h4> 

<ul>

  <li><label for="cat46" class="checkbox"><input type="checkbox" id="cat46" name="cntnt01cd_categories[]" value="46"/> Auto Service or Auto Repair</label></li>

  <li><label for="cat48" class="checkbox"><input type="checkbox" id="cat48" name="cntnt01cd_categories[]" value="48"/> Auto Glass</label></li>                                          
</ul>
有帮助吗?

解决方案

use prop() instead of attr() and data() to get the HTML5 data attribite

 $('input.checkbox').click(function() {
   var parent = $(this).data('parent');

   $('#'+parent).prop('checked', true);
});

updated (I guess you will be needing this too)

updated version : if any of the checkbox inside a group is checked parent is checked else unchecked.

$('input.checkbox').click(function() {
   var parent = $(this).data('parent');
   var checked =false;
   $(this).parents('ul').find(':checkbox').each(function(){
     if(this.checked){
        checked = true;
        return;
     }
  });
 $('#'+parent).prop('checked', checked);
});

i figured out your second group in the fiddle is not working since you haven't stated the input class and data attribute for this group . and yes you can select all input checkbox with $(':checkbox') rather than giving class to all the input checkbox element and calling class selector(less code) .

fiddle

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top