4

I cant figure out, why this code does not work as expected:

var $obj = jQuery('<div>xx<input type="text" value="" />xx</div>');
$obj.find('input').val('testing');
console.log($obj.html());

The resulting output is without any change - i.e. no change in value. But append() and other functions works fine. What could be wrong?

Luke
  • 43
  • 3
  • 2
    Setting the `.value` property did never change the `value` attribute that gets serialized by `html()`. – Bergi Aug 13 '13 at 13:03
  • possible duplicate of [Why aren't some technically serializable input properties serializable?](http://stackoverflow.com/questions/11778123/why-arent-some-technically-serializable-input-properties-serializable) – Bergi Aug 13 '13 at 13:17

2 Answers2

7

value is an atrribute of the input dialog.

Doing .val(...) changes the value property and not the value in the DOM.

See here for the differences between properties and attributes.


If you wanted to see a physical change in the value attribute you could do something like this:

var $obj = jQuery('<div>xx<input type="text" value="" />xx</div>');
$obj.find('input').attr('value','testing');
console.log($obj.html());

Demo: http://jsfiddle.net/maniator/YsZLt/

Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303
0

The "value"-attribute maps to .defaultValue property.

There is no attribute that maps to .value property. However, on non-dirty inputs inputs, you can set the attribute "value" (and obviously, .defaultValue) and that will be reflected in the property .value.

Since your input is non-dirty, you can do this

var $obj = jQuery('<div>xx<input type="text" value="" />xx</div>');
$obj.find('input').prop('defaultValue', 'testing');
console.log($obj.html());
//xx<input type="text" value="testing">xx
Community
  • 1
  • 1
Esailija
  • 138,174
  • 23
  • 272
  • 326