Strontium_99
Strontium_99

Reputation: 1803

Counting inputs with values on change using jquery

Why doesn't this work? It tells me I have 1 input with a value on loading, which is correct. But if I add or remove a value, it still says I have 1 input with a value.

<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function(){

alert($('#myForm input[type=text][value!=""]').length);

$('#myForm input[type=text]').change(function(){
    alert($('#myForm input[type=text][value!=""]').length);
})

});
</script>
</head>

<body>
<div id="myForm">
   <input type="text" value="foo" name="f1">
   <input type="text" value="" name="f2">
</div>
</body>

FIDDLE

Upvotes: 1

Views: 1199

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115212

You are selecting element which have attribute value equals ''(empty string) , the attribute value is not changing it's just updating it's value property of the dom object. So use filter() for filtering based on updated value

<head>
  <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
  </script>
  <script>
    $(document).ready(function() {

      alert($('#myForm input[type=text][value!=""]').length);

      $('#myForm input[type=text]').change(function() {
        alert($('#myForm input[type=text]').filter(function() {
          return this.value == '';
        }).length);
      })

    });
  </script>
</head>

<body>
  <div id="myForm">
    <input type="text" value="foo" name="f1">
    <input type="text" value="" name="f1">
  </div>
</body>

Upvotes: 2

Related Questions