最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Append value to an input field in Javascript - Stack Overflow

programmeradmin4浏览0评论

Here i'm trying to append some text to an input field but everytime the old value gets replaced with new value.

HTML

<input type="text" id="taginput" class="input" name="tags">

Javascript

function update(i){
 document.getElementById('taginput').value = i.innerHTML;
  }

no jquery please.

Here i'm trying to append some text to an input field but everytime the old value gets replaced with new value.

HTML

<input type="text" id="taginput" class="input" name="tags">

Javascript

function update(i){
 document.getElementById('taginput').value = i.innerHTML;
  }

no jquery please.

Share Improve this question asked Jul 20, 2017 at 13:27 Ajmal RasiAjmal Rasi 951 gold badge1 silver badge7 bronze badges 2
  • 1 document.getElementById('taginput').value += i.innerHTML; – Satpal Commented Jul 20, 2017 at 13:29
  • If you call update multiple times you're going to append all the html inside i again and again so it'll have many, many duplicates. Maybe that's what you want, but if not you may need to rethink your strategy. – Khauri Commented Jul 20, 2017 at 13:33
Add a ment  | 

4 Answers 4

Reset to default 9

You have to get the old value first, and then add to it

function update(i){
    var elem = document.getElementById('taginput');
    var old  = elem.value;
    elem.value = old + i.innerHTML;
}

or you could add it to with += directly

elem.value += i.innerHTML;

const input = document.querySelector('input');
input.value += ' doe';
alert(input.value);
<input value="john" type="text">

innerHTML makes no sense as the input's value.

Use Addition assignment.

function update(i){
    let elem = document.getElementById('taginput');
    elem.value = elem.value + i.innerHtml; 
    // Or elem.value += i.innerHtml;
    // elem.value = elem.value.concat(i.innerHtml)
}

<html>
<head>
</head>
<body>
<input id="my_msg" type="text">
</body>
<script>
document.getElementById('my_msg').value = "text-value";
</script>
</html>

document.getElementById('my_msg').value = "text-value";

Use above script to append 'text-value' to input field.

Thanks

发布评论

评论列表(0)

  1. 暂无评论