Toggle Checkboxes on/off
I have the following:
$(document).ready(function()
{
$("#select-all-teammembers").click(function() {
$("input[name=recipients\\[\\]]").attr('checked', true);
});
});
I'd like the id="select-all-teammembers"
when clicked to toggle between checked and unchecked. Ideas? that aren't dozens of lines of code?
You can write:
$(document).ready(function() {
$("#select-all-teammembers").click(function() {
var checkBoxes = $("input[name=recipients\\[\\]]");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});
});
Before jQuery 1.6, when we only had attr() and not prop(), we used to write:
checkBoxes.attr("checked", !checkBoxes.attr("checked"));
But prop()
has better semantics than attr()
when applied to "boolean" HTML attributes, so it is usually preferred in this situation.
//this toggles the checkbox, and fires its event if it has
$('input[type=checkbox]').trigger('click');
//or
$('input[type=checkbox]').click();
I know this is old but the question was a bit ambiguous in that toggle may mean each checkbox should toggle its state, whatever that is. If you have 3 checked and 2 unchecked, then toggling would make the first 3 unchecked and the last 2 checked.
For that, none of the solutions here work as they make all the checkboxes have the same state, rather than toggle each checkbox's state. Doing $(':checkbox').prop('checked')
on many checkboxes returns the logical AND between all .checked
binary properties, i.e. if one of them is unchecked, the returned value is false
.
You need to use .each()
if you want to actually toggle each checkbox state rather than make them all equal, e.g.
$(':checkbox').each(function () { this.checked = !this.checked; });
Note that you don't need $(this)
inside the handler as the .checked
property exists in all browsers.
Here is another way that you want.
$(document).ready(function(){
$('#checkp').toggle(
function () {
$('.check').attr('Checked','Checked');
},
function () {
$('.check').removeAttr('Checked');
}
);
});
I think it's simpler to just trigger a click:
$("#select-all-teammembers").click(function() {
$("input[name=recipients\\[\\]]").trigger('click');
});