Javascript: filling inputs with text without overwriting the text that is already there

百般思念 提交于 2019-12-25 01:28:46

问题


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

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