Modifying “value” attribute of “text” input not working using JavaScript

微笑、不失礼 提交于 2020-04-16 02:10:00

问题


I have a question regarding a text input field, whose value is modified by a JavaScript function. Here is a simplified snippet of my code:

<!doctype html>
<html>
    <meta charset="utf-8">
    <head>
        <title>Test Page</title>
        <script>
            function runScript()
            {
                document.getElementById("result").innerHTML = "Changing Text Input Value to Name 2";
                document.getElementById("name_input0").value = "Name 2";
                document.getElementById("name_hidden0").value = "Name 2";
            }
        </script>
    </head>
    <body>
    <input type="hidden" id="name_hidden0" value="Name 1"/>
    <input type="text" name="name_enter0" id="name_input0" value="Name 1"/>
    <input type="button" value="Run Script" onClick="runScript()"/>
    <div id="result"></div>
    </body>
</html>

When the page loads, the text and hidden input are both populated with the value "Name 1". When I click the button, the page looks like this:

Page View After Running JavaScript

which makes perfect sense, however, if I look at the source code using the Developer Tools (I tried Firefox and Chrome) and look at the HTML code, I see the following:

Underlying HTML after Running JavaScript

Why did the "value" attribute of the text input field not change in the underlying HTML, but the hidden input "value" did?


回答1:


For text inputs:

The HTML value attribute sets the default value.

The DOM value property holds the current value.

There isn't a 1:1 mapping between them.



来源:https://stackoverflow.com/questions/31482807/modifying-value-attribute-of-text-input-not-working-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!