Javascript:用文本填充输入而不覆盖已经存在的文本
Javascript: filling inputs with text without overwriting the text that is already there
我正在尝试创建一个按钮,在单击时将文本添加到输入中,但它没有添加文本,而是覆盖了已经输入的文本。我需要帮助。
这是代码:
<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>
我应该这么简单:
input.value += "text overwrites instead of adding";
+= 运算符向变量添加内容,而 = 分配新值。
想象一下:
var a=8;
a+=4;
console.log(a);
痕迹 12
如果我们这样做:
var a=8;
a=4;
console.log(a);
痕迹 4
您需要获取现有输入的值 - 将新内容附加到它,然后将新值传递回输入。
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>
我正在尝试创建一个按钮,在单击时将文本添加到输入中,但它没有添加文本,而是覆盖了已经输入的文本。我需要帮助。 这是代码:
<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>
我应该这么简单:
input.value += "text overwrites instead of adding";
+= 运算符向变量添加内容,而 = 分配新值。
想象一下:
var a=8;
a+=4;
console.log(a);
痕迹 12
如果我们这样做:
var a=8;
a=4;
console.log(a);
痕迹 4
您需要获取现有输入的值 - 将新内容附加到它,然后将新值传递回输入。
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>