Check all checkboxes on page load with jQuery

夙愿已清 提交于 2019-12-18 21:19:11

问题


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


回答1:


$(function(){
    $('#thediv input:checkbox').attr('checked', 'checked');
});



回答2:


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);



回答3:


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 :)




回答4:


This is work in firefox v.17.01. Not yet tested it on another browsers.

// Select and Check checkboxes on load

$('#enable, #enable1, #enable2, #enable3').attr('checked', 'checked');

See the example:

JS FIDDLE



来源:https://stackoverflow.com/questions/3126736/check-all-checkboxes-on-page-load-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!