views:

769

answers:

4

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

I have tried the following but with no luck.

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

Using $('.class[value="1"]') technically works, however, if the values in the text input are changed after load, it still counts it as its default load value.

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

I had no luck at all using $('.class:contains("1")')

It seems very simple, but has so far eluded me.

+4  A: 

This example demonstrates that this works:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
<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 just loop:

var matches = 0;
$(":input.class").each(function(i, val) {
  if ($(this).val() == '1') {
    matches++;
  }
});
cletus
I thought JQuery may have a shorthand one liner, however, it works. Thank you!
ticallian
A: 

Sounds like you might be needing to do the count in an event handler, possibly a handler for the keyup event (or maybe keypress)

$('.class').keyup(function(e) {
    alert($('.class[value=1]').length);
});
Russ Cam
+1  A: 

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

k=0;
$('.class').each(function(i, e) {
  if ($(e).val() == "1") k++;
});
Scott Evernden
A: 
$(':input.class').filter(function() {
    return $(this).val() == '1'
})
meder