On page load, using jQuery how can I select all check boxes in a specific div automatically?
What redquare has will work, but it's a better idea overall to use true
/false
with these since that's how they're normalized, here are a few examples of why this is a handy habit to follow. For example:
$('#myDiv :checkbox').attr('checked', 'checked');
alert($('#myDiv :checkbox').attr('checked')); //this alerts true, not "checked"
You can test this here
Instead, get in the habit of passing a boolean, which is a lot more versatile, for example:
$(function() {
$('#myDiv :checkbox').attr('checked', true);
});
This allows a lot more flexibility in more terse code, for example, say we had a "Check All" checkbox on the top, how would that look?
$('#checkAll').change(function() {
if(this.checked) {
$('#subTable :checkbox').attr('checked', 'checked');
} else {
$('#subTable :checkbox').removeAttr('checked', 'checked');
}
});
Now we've had to bring a new function in to do the work, .removeAttr(). To be fair, this is even how the jQuery documentation does it in the example. But, you can cut that down greatly if you take advantage of the normalization jQuery does internally, like this:
$('#checkAll').change(function() {
$('#subTable :checkbox').attr('checked', this.checked);
});
This is just something to keep in mind as you code, the same rules appy to .attr('disabled')
. There are other areas that normalization occurs as well...probably events being the most extensive of them, if you're curious you can see that here, it's already done for you, use it :)