1

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

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

@user1001421 : glad to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.