I have a table whose values are generated dynamically with PHP. Each row in the table has a checkbox. 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 thecheckedattribute totrueand returns a jQuery object which always evaluates totrue.Maybe you want
which inverts the
checkedvalue for each checkbox.If you want to select or deselect all at once, you could do: