On page load, using jQuery how can I select all check boxes in a specific div automatically?
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("myDiv");
var inputs = div.getElementsByTagName("input");
for (var i = 0, len = inputs.length; i < len; ++i) {
if (inputs[i].type == "checkbox") {
inputs[i].checked = true;
}
}
UPDATE
Since the release of jQuery 1.6 and prop()
, there is a sane way to do this in jQuery:
$("#myDiv input:checkbox").prop("checked", true);
$(function(){
$('#thediv input:checkbox').attr('checked', 'checked');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With