Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check all checkboxes on page load with jQuery

On page load, using jQuery how can I select all check boxes in a specific div automatically?

like image 561
say Avatar asked Jun 27 '10 07:06

say


2 Answers

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);
like image 176
Tim Down Avatar answered Sep 30 '22 05:09

Tim Down


$(function(){
    $('#thediv input:checkbox').attr('checked', 'checked');
});
like image 43
redsquare Avatar answered Sep 30 '22 06:09

redsquare