Reputation: 1093
I've created a search function on a website I'm developing but I'm stuck on this part. The search function has a list of categories which the user can check or uncheck in order to filter through the items. The options are almost identical to the way Coursera has implemented their search function. I would like to have all the other checkboxes unchecked when the All Categories option is checked and have the All Categories checkbox unchecked when anything else is unchecked. That sounds a bit confusing but it's exactly what that website has implemented.
Here's an example of the code:
<div class="filter-grade">
<label class="checkbox">
<input type="checkbox" id="grade-all" name="grade[]" value="0" checked><b>All Grades</b>
</label>
<label class="checkbox">
<input type="checkbox" id="grade-9" name="grade[]" value="9">Grade 9
</label>
<label class="checkbox">
<input type="checkbox" id="grade-10" name="grade[]" value="10">Grade 10
</label>
<label class="checkbox">
<input type="checkbox" id="grade-11" name="grade[]" value="11">Grade 11
</label>
<label class="checkbox">
<input type="checkbox" id="grade-12" name="grade[]" value="12">Grade 12
</label>
</div>
Upvotes: 1
Views: 1817
Reputation: 20514
This code also doing the trick .Get in the right path from the answer of ArraryKnigh. You can also check the fiddle :
$('.group :checkbox').filter("[class!='group-all']").on('change', function() {
var parentDiv=$(this).parent();
$('.group-all',parentDiv ).attr('checked',false);
});
$('.group :checkbox').filter("[class='group-all']").on('change', function() {
var parentDiv=$(this).parent();
$('input',parentDiv ).attr('checked',false);
$(this).attr('checked',true);
});
Upvotes: 2
Reputation: 7356
Despite my comment, I built out a fiddle: http://jsfiddle.net/ctnCn/5/
$('.group input').on('change', function() {
var $inputs = $(this).siblings('input').add(this),
$checked = $inputs.filter(':checked'),
$all = $inputs.eq(0),
index = $inputs.index(this);
(index === 0 ? $checked : $all).removeAttr('checked');
if(index === 0 || $checked.length === 0) {
$all.attr('checked', 'checked');
}
});
Update to be project specific: http://jsfiddle.net/ctnCn/6/
$('.filter-grade input').on('change', function() {
var $inputs = $(this).closest('div').find('input'),
Though I would like to point out that this is not the standard usage of the label element. I would suggest changing your markup to have labels and inputs be siblings (and use the "id" and "for" attributes to link them). Take a look at this reference: http://www.w3schools.com/tags/tag_label.asp My previous fiddle also provides an example of the standard markup convention.
Upvotes: 3