0

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'.

1 Answer 1

1

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

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

4 Comments

While that code does work, the other should work as well, right? I mean it is obviously being set, otherwise the first console log wouldn't show 'world'.
What's the other ? first console displays world because .attr() updated the attribute value.
Sorry, I meant my OG code. The OG first console displays world as well.
Ah, makes sense. Completely forgot input wasn't part of the DOM.

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.