JQuery: number of inputs with a specific value

I need to count the number of text inputs with a value of 1.

I tried the following but no luck.

$('.class[value="1"]').length $('.class:contains("1")').length 

Using $('.class[value="1"]') technically works, however, if the values ​​in the text input change after loading, it still considers it the default load value.

I took a long shot using the .live click event to get the current value, but still no luck.

I'm out of luck using $('.class:contains("1")')

It seems very simple, but still eluded me.

+6
javascript jquery jquery-selectors
source share
3 answers

This example shows that this works:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { $("#btn").click(function() { alert($(":input[value='1']").length); }); }); </script> </head> <body> <input type="text"> <input type="text"> <input type="text"> <input type="button" id="btn" value="How many?"> </body> </html> 

Alternatively, you can simply execute a loop:

 var matches = 0; $(":input.class").each(function(i, val) { if ($(this).val() == '1') { matches++; } }); 
+14
source share

You need to iterate with $ .each () if you want val () values:

 k=0; $('.class').each(function(i, e) { if ($(e).val() == "1") k++; }); 
+4
source share
 $(':input.class').filter(function() { return $(this).val() == '1' }) 
+1
source share

All Articles