Robbie Robbie - 22 days ago 14
jQuery Question

Setting Input value in jquery variable

How would you change or set the value of an input in a jquery variable object.
For example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
htmlString = '<div><input name="hello" value="AAAAAAAA" /> </div>';
$htmlString = $(htmlString);
$htmlString.find('[name="hello"]').val('world')
console.log( $htmlString.find('[name="hello"]').val() );
console.log( $htmlString.prop('outerHTML') );
</script>


The value of [name="hello"] shows to be 'world' in the first console.log, but in the second it shows that it is still 'AAAAAAAA'.
I am needing it to stay as 'world'.

Answer

Use jQuery's .attr() to set new attribute value, witch call .setAttribute() in pure js and both of them make changes in DOM structure.

Why first console displays "world" as well ?

e.g. if you set value of input like

inputID.value = "world";
//value changed but if you try to view source HTML you see no changes
inputID.setAttribute("value","world");
//here your source code changed

Also in jQuery

inputID.val("world");
//value changed but if you try to view source HTML you see no changes
inputID.attr("value","world");
//here your source code changed

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
htmlString = '<div><input name="hello" value="AAAAAAAA" /> </div>';
$htmlString = $(htmlString);
$htmlString.find('[name="hello"]').attr("value",'world');
console.log( $htmlString.find('[name="hello"]').val() );
console.log( $htmlString.prop('outerHTML') );
</script>

Comments