AnonyMouse
AnonyMouse

Reputation: 18630

jquery count elements with a particular class that have value greater than zero

Hi say I have some inputs:

<input type="Text" class="myclass" value="0" />
<input type="Text" class="myclass" value="7" />
<input type="Text" class="myclass" />
<input type="Text" class="myclass" value="2" />

And I want to count the number of inputs with class myclass that have a value greater than zero how would I go about that. In the scenario above the output I would want would be 2.

So far I have $(".myclass").filter().length

However I'm not sure what should go in filter or it I should even be using it.

Upvotes: 1

Views: 1760

Answers (3)

Joe
Joe

Reputation: 15528

Use this:

$(".myclass").filter(function(){
    return +this.value > 0;
}).length;

+ casts the value to a number and then it just returns true if the value is greater than one and false if otherwise. A function is passed to .filter(), this loops through each match. If the function returns false then the element is removed from the set so you're just left with elements whose value is greater than zero.

Here's a demo: http://jsfiddle.net/88zH3/

Upvotes: 1

Razor
Razor

Reputation: 29628

$(".myclass").filter(function(el, i){
    return parseInt( $(el).val(), 10 ) > 0;
}).length;

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

Try this:

var count=$(".myclass").filter(function(){
     return $(this).val() >0;
}).length

Upvotes: 0

Related Questions