Reputation: 736
I have multiple checkboxes. I want to check and uncheck some of them or all when I click on appropriate button.
For example when I click over "Check All" button I want to be checked all buttons. When I click over "Male" button I want to be checked only checkboxes where "class" is equal to "male". When I click over "Female" button I want to be checked only checkboxes where class is equal to "female". When I click over "None" button I want to be checked only checkboxes where class is equal to "none". How can I do that with jquery?
<br>
<div>
<input type="checkbox" class="check_all"> Check all
<input type="checkbox" class="check_all_females"> Females
<input type="checkbox" class="check_all_males"> Males
<input type="checkbox" class="check_all_none"> None
</div>
<input type="checkbox" class='male'> John<BR>
<input type="checkbox" class='male'> Maria<BR>
<input type="checkbox" class='male'> Ali<BR>
<input type="checkbox" class='male'> Tural<BR>
<input type="checkbox" class='female'> John<BR>
<input type="checkbox" class='female'> Fuass<BR>
<input type="checkbox" class='female'> Jadsa<BR>
<input type="checkbox" class='none'> Dasda<BR>
<input type="checkbox" class='none'> Wers<BR>
<input type="checkbox" class='none'> Saqa<BR>
Upvotes: 0
Views: 928
Reputation: 49949
Do this:
$(function(){
$("div.mains input:checkbox").click(function(){
var rel = $(this).attr("rel"),
checked = $(this).is(":checked");
switch(rel)
{
case "all":
if(!checked)
{
$(".sub input:checkbox").removeAttr("checked");
}
else
{
$(".sub input:checkbox").attr("checked", "checked");
}
break;
default:
if(!checked)
{
$(".sub input." + rel).removeAttr( "checked");
}
else
{
$(".sub input." + rel).attr( "checked", "checked");
}
}
});
});
HTML
<br>
<div class="mains">
<input type="checkbox" rel="all" class="check_all"> Check all
<input type="checkbox" rel="female" class="check_all_females"> Females
<input type="checkbox" rel="male" class="check_all_females"> Males
<input type="checkbox" rel="none" class="check_all_females"> None
</div>
<div class="sub">
<input type="checkbox" class='male'> John<BR>
<input type="checkbox" class='male'> Maria<BR>
<input type="checkbox" class='male'> Ali<BR>
<input type="checkbox" class='male'> Tural<BR>
<input type="checkbox" class='female'> John<BR>
<input type="checkbox" class='female'> Fuass<BR>
<input type="checkbox" class='female'> Jadsa<BR>
</div>
Try out this fiddle: http://jsfiddle.net/2R2CC/
Upvotes: 7