开发者

Selecting from a list of previously selected elements via jQuery

I'm having a bit of a brain fart here, and hoping someone can help me find a 1-line solution to this problem, without having to call .each().

So I get a list of all checkboxes within a container like this:

var checkboxes = $(':checkbox', '#surveyModal');

At some point later, I need to find out if any (or none) of the checkboxes are checked within that list.

I expected something like these to work:

$(':checked', checkboxes)
// or
checkboxes.attr(':checked')
// or    
$(checkboxes).attr(':checked')

But it doesn't. The only thing I've had success with is calling each() and 开发者_如何学编程then checking each individually. But that means I'll have to keep a separate variable (.e.g. someAreChecked at a higher-level scope, which I don't feel is optimal.

    checkboxes.each(function () {
        if ($(this).attr('checked')) {
            someAreChecked = true;
        }
    });

I was hoping that I can easily in a single line do such a check:

if (checkboxes.('get checked count') == 0)
{
}

Thanks in advance.


The filter function is what you're looking for :)

checkboxes.filter(':checked').length;


.attr returns the value of an attribute, and you have to pass the attribute's name to it, not a selector.

Just use .is instead.

Description: Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

$(checkboxes).is(':checked')


This should do it:

$("input[type=checkbox][checked]").length 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜