Reputation: 18630
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
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
Reputation: 29628
$(".myclass").filter(function(el, i){
return parseInt( $(el).val(), 10 ) > 0;
}).length;
Upvotes: 0
Reputation: 171669
Try this:
var count=$(".myclass").filter(function(){
return $(this).val() >0;
}).length
Upvotes: 0