0

Given the html of:

<input type="text" name="name1" value="">

I run console.log( $('input[value='']).length ); and get 1.

If I then enter a value in the field and run console.log( $('input[value='']).length ); again I still get 1. What gives? Do selectors only work on the original values of forms?

If I set the value from start, i.e.

<input type="text" name="name1" value="">

... I get the expected 0 when I run console.log( $('input[value='']).length );

There's a workaround for jquery < 1.8.3, (using input:text[value=''] instead), but >= 1.9, this doesn't work either.

Fiddle http://jsfiddle.net/nZ27z/10/

zoomix
  • 915
  • 1
  • 6
  • 11

2 Answers2

1

When someone types in a field, the value property changes, not the value attribute.

You can do something like this:

var emptyCount = $('input').filter(function() { 
    return this.value === ''; 
}).length;
Jason P
  • 26,984
  • 3
  • 31
  • 45
  • So when I change the value, manually by entering something in the field or automatically in jquery, I'm only changing the property. Does that make attributes immutable? Or can you change attributes too? (And what's the point of the separation? =) Just curious. – zoomix Feb 05 '14 at 17:44
  • 1
    You can change attributes, using `.attr()`. Here is an SO question with several very detailed answers on the difference between attributes and properties, and `.attr()` and `.prop()`: http://stackoverflow.com/questions/5874652/prop-vs-attr – Jason P Feb 05 '14 at 17:47
0

With this code if u change the value of the imput your length after running it again will change.

console.log($( "input[name='name1']").val().length);
alecellis1985
  • 131
  • 2
  • 15