mitomed
mitomed

Reputation: 2066

Jquery checked selector within variable

I'm struggling with this, not even found if it's possible..

Having a variable like this

var this.$others = $("input:checkbox[name *='" + container + "']");

that stores a list of checkboxes, I want to check in another function the number of those that are checked. I can do that:

 var numberOfNotChecked = self.$others.not(':checked').length;

and it works fine, but I thought it would be more clear for the rest of the code which is going to use this variable to have the opposite one (i.e. the number of checkboxes checked)

So I'm trying this

var numberOfChecked = self.$others.find(':checked').length;

And it doesn't come as they are always 0. Any idea?

Thanks

Upvotes: 0

Views: 238

Answers (3)

Manoj
Manoj

Reputation: 56

Instead of find use filter function :

var numberOfChecked = self.$others.filter(':checked').length;

Upvotes: 0

webdeveloper
webdeveloper

Reputation: 17288

Try filter, not find:

var numberOfChecked = self.$others.filter(':checked').length;

You are using .find() which looks for elements within an element. For example:

<div id="bar"><p>some text</p></div>
<script>
    var foo = $('#bar').find('p'); // foo.length = 1
</script>

On the other hand, .filter() returns a jQuery collection of elements which match the given selector from an existing collection. (Exactly what you're trying to do).

Upvotes: 3

Dhaval Bharadva
Dhaval Bharadva

Reputation: 3083

Replace:

var numberOfChecked = self.$others.find(':checked').length;

To:

var numberOfChecked = self.$others.filter(':checked').length;

JSFIDDLE DEMO

Upvotes: 0

Related Questions