How To Toggle All Checboxes With JQuery
I have a table whose values are generated dynamically with PHP. Each row in the table has a checkb开发者_运维百科ox. In the table is a header column, that has a "Accept All" button.
When a user clicks the "Accept All" button, all select boxes are checked. However, I want to add a toggle-like functionality: if no boxes are checked, then pressing the button selects all; if all boxes are checked, then pressing the button would unselect all.
Here's my JQuery code for select all:
//Approves all
$('#approve_all_questions').click(function () {
$("INPUT[type='checkbox']").attr('checked', true);
});
I'm having trouble getting it to toggle correctly. I've tried this:
//Toggle
$('#approve_all_questions').click(function () {
if($("INPUT[type='checkbox']").attr('checked', true))
{
$("INPUT[type='checkbox']").attr('checked', false);
}
else
{
$("INPUT[type='checkbox']").attr('checked', true);
}
});
But that doesn't work.
TIA.
$("INPUT[type='checkbox']").attr('checked', true)
sets the checked
attribute to true
and returns a jQuery object which always evaluates to true
.
Maybe you want
$("input[type='checkbox']").prop('checked', function(i, val) {
return !val;
});
which inverts the checked
value for each checkbox.
If you want to select or deselect all at once, you could do:
var $boxes = $("input[type='checkbox']"),
$unselected = $boxes.not(function(){
return this.checked;
});
// if there are any unselected boxes, it selects all, else it deselects all
$boxes.prop('checked', $unselected.length > 0);
http://jsfiddle.net/6mK9q/1/
just one parameter needed, second one sets checked to true and returns object (which is considered as true)
Here's another slab of code for you with a working demo: http://jsbin.com/agomuc/edit.
Please notice the use of .live()
, if you want to use .click()
you'll have to put your handler into
$(document).ready(function(){
// handler here
});
i prefer my solution:
$(".selectAllCheckBox").live("click", function() {
$("input[type='checkbox']").each(function() {
if($(this).attr('checked')){
$(this).attr('checked', false);
} else {
$(this).attr('checked', true);
}
});
});
;)
精彩评论