Reputation: 12512
I have the following function that checks/unchecks all checkboxes on the page by selecting one
$("#checkall").click(function() {
var checked_status = this.checked;
$("input:checkbox").each(function() {
this.checked = checked_status;
});
});
I need to modify it in such a way that if all are selected by clicking checkall and then one is unchecked the #checkall gets unchecked as well. Or do I need to create a separate function for this?
Also when NONE of the checkboxes is selected I need to add a class to another element.
$("#myElement").addClass("disabled");
Putting it all together sort of complicates things for me.
Upvotes: 1
Views: 235
Reputation: 9031
I would use change event.
Is this what you are after?:
<div class="checkall">
<input type="checkbox" id="checkall">
</div>
<div id="list">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
and jquery:
var checkboxes = $(":checkbox", "#list").change(function() {
var allIsChecked = checkboxes.length === checkboxes.filter(":checked").length;
checkAll[0].checked = allIsChecked;
});
var checkAll = $("#checkall").change(function() {
checkboxes.prop("checked",this.checked);
});
demo (if you are using jquery 1.6+): http://jsbin.com/ezofal/edit
added the #MyElement class toggle in this link: http://jsbin.com/ezofal/2/edit
Upvotes: 3
Reputation: 78520
$("input:checkbox").click(function() {
var checked_status = this.checked;
if($(this).is("#checkall")) {
$("input:checkbox").each(function() {
this.checked = checked_status;
});
} else {
$("#checkall").attr('checked', ($("input:checkbox:not(#checkall):checked").length ==
$("input:checkbox:not(#checkall)").length));
}
});
tested
Some ideas stolen from @Toukakoukan
Upvotes: 1
Reputation: 1248
$(document).ready(function(){
$("#checkall").click(function() {
var checked_status = this.checked;
$("input:checkbox").each(function() {
this.checked = checked_status;
});
});
$('input[type=checkbox]:not(#checkall)').change(function(){
if($('input[type=checkbox]').length != $('input[type=checkbox]:checked').length){
$('#checkall').attr('checked', false);
}
});
});
Upvotes: 2
Reputation: 3981
var checked_status = false;
$("#checkall").click(function() {
checked_status = this.checked;
$("input:checkbox").each(function() {
this.checked = checked_status;
});
});
$("input:checkbox").click(function(){
if(checked_status == true) {
$('#checkall').checked = false;
}
});
Upvotes: 1