On page load, using jQuery how can I select all check boxes in a specific div automatically?
$(function(){
$('#thediv input:checkbox').attr('checked', 'checked');
});
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"
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 :)
People seem genuinely confused about how to do this in jQuery. Checking a checkbox is much easier and more efficient without it. The following uses jQuery's strengths of selecting and iterating over a list of nodes combined with the couldn't-be-simpler DOM checked
property of checkbox elements:
$("#myDiv input:checkbox").each(function() {
this.checked = true;
});
It's not too hard to cut out jQuery altogether in this case:
var div = document.getElementById("theDiv");
var inputs = div.getElementsByTagName("input");
for (var i = 0, len = inputs.length; i < len; ++i) {
if (inputs[i].type == "checkbox") {
inputs[i].checked = true;
}
}