$(element).val('newvalue') Is Not Reflected in element.outerHTML

Hol*_*ger 1 javascript jquery

I am unable to see the value attribute of input elements when using element.outerHTML. Problem is with all input types; example HTML:

<input type="text" id="copy-paste-textarea" />
Run Code Online (Sandbox Code Playgroud)

Example JavaScript:

<script type="text/javascript">
$('#copy-paste-textarea').on('click', function(e) {
    console.log("Text area's outerHTML???" + this.outerHTML + "|");
        // Output: <input id="copy-paste-textarea" type="text">

    $(this).val('hello!');
    $(this).addClass('world!');

    console.log("Text area's outerHTML???" + this.outerHTML + "|");
        // Output: <input id="copy-paste-textarea" class="world!" type="text">
});
</script>
Run Code Online (Sandbox Code Playgroud)

When I run this code above, I see that the change from addClass() is reflected in this.outerHTML, but the change of val() is not. BUT -- I see that the field is indeed actually being populated with the values. I want output to be this:

// Output: <input id="copy-paste-textarea" value="hello!" class="world!" type="text">
Run Code Online (Sandbox Code Playgroud)

The html() function produces the same results. I would like a solution that works on any input type (select, textarea, etc.).

Similar answer here will only work on textareas: Cannot get outerHTML/value of a dynamically added textarea

Sco*_*cus 5

This is because elements have "properties", which store dynamic information only in memory as expressed by the JavaScript DOM object and they also have "attributes" where the element's actual markup is recorded in memory and is accessible via the HTML parser.

  • JQuery's .val() method writes data to an in-memory only property.
  • 为了得到你想要的,你必须使用JQuery的方法设置value 属性.attr()

属性和属性之间微妙但重要的区别导致了 JQuery.prop().attr()方法之间的混淆。

$('#copy-paste-textarea').on('click', function(e) {
    console.log("input field's outerHTML???" + this.outerHTML + "|");

    // You must set the attribute for it to be picked up in the HTML
    $(this).attr("value", "hello!");
    $(this).addClass('world!');

    console.log("input field's outerHTML???" + this.outerHTML + "|");
});

// For a textarea, you need to get the content of the tags with .text()
$('textarea').on('click', function(e) {
    console.log("Text area's outerHTML???" + this.outerHTML + "|");

    // You must set the attribute for it to be picked up in the HTML
    $(this).text("value", "hello!");
    $(this).addClass('world');
    console.log("Text area's outerHTML???" + this.outerHTML + "|");
});
Run Code Online (Sandbox Code Playgroud)
.world {
  background-color:yellow;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="copy-paste-textarea">

<textarea></textarea>
Run Code Online (Sandbox Code Playgroud)