user1001421 user1001421 - 6 months ago 10
Javascript Question

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

Answer

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>

Comments