问题
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:
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:
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