JQuery.val () not working on html chunk?

I cannot understand 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 result does not change, i.e. no change in meaning. But append() and other functions work fine. What could be wrong?

+4
source share
2 answers

value is the atrribute of the input dialog.

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

See here for differences between properties and attributes.


If you want to see the physical change in the value attribute, you can 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/

+7
source

The "value" attribute displays the .defaultValue property.

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

Since your entrance is not dirty, you can do it

 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 
0
source

Source: https://habr.com/ru/post/1496801/


All Articles