问题
I am trying to create a button that adds text to input when clicked, but instead of adding text it overwrites the text that's already typed in there. I need help. Here's the code:
<script>
function autoFill() {
var input = document.getElementsByTagName("INPUT")[0]
input.value = "text overwrites instead of adding";
}
</script>
<input type="input"></input>
<button type="button" onclick="autoFill()">fill it!</button>
回答1:
I should be as simple as:
input.value += "text overwrites instead of adding";
The += operator adds something to a variable while = assigns a new value.
Picture this:
var a=8;
a+=4;
console.log(a);
traces 12
If we do it like this:
var a=8;
a=4;
console.log(a);
traces 4
回答2:
You need to get the value of the input that exists - append the new content to it and then pass the new value back to the input.
function autoFill() {
var input = document.getElementsByTagName("INPUT")[0];
var val = input.value;
var newContent = "new content";
input.value = val + " " + newContent;
}
<input type="text" value="Sample text">
<button type="button" onclick="autoFill()">fill it!</button>
来源:https://stackoverflow.com/questions/54935862/javascript-filling-inputs-with-text-without-overwriting-the-text-that-is-alread