开发者

Is there a clean way in jQuery to check if all elements in a collection fulfil a requirement?

I have a bunch of checkboxes and I want to check if all of them are checked.

I realize that I can do this by storing state in an external variable and then iterate over the collection but I want to see if maybe there is a cleaner way of doing it? Here's a fiddle for you to try it.

http://jsfiddle.开发者_JAVA技巧net/ys8FJ/


Yes search for all not checked boxes:

if ($('input:checkbox:not(:checked)').length == 0) alert('checked');

Reversed logic - if there isn't any unchecked box then all boxes are checked ;)


Just to try to answer the question in the title, "check if all elements in a collection fulfil a requirement".

A general case might be to create a method like this:

jQuery.fn.extend({
    isTrueForAll: function(selector) {
        return $(this).not(selector).length == 0;
    }
});

Then you could use it like this:

if($("input:checkbox").isTrueForAll(":checked")){
    alert("Yep");
}

Or like this:

if($("option").isTrueForAll(":selected")){
    alert("Yep");
}

Or even compare classes:

if($("p").isTrueForAll(".red")){
    alert("Yep");
}


Try this code:

Addeded name="a1" for each item:

<div>
    <input type="checkbox" checked="checked" name="a1" />
    <input type="checkbox" checked="checked" name="a1" />
    <input type="checkbox" checked="checked" name="a1" />
</div>

$(function(){
    //nice one line check if all boxes are checked
    alert($('input[name=a1]:checked').length);
});


How about this:

$(':checkbox:checked').length == $(':checkbox').length;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜