Ajmal Rasi
Ajmal Rasi

Reputation: 95

Append value to an input field in Javascript

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.

Upvotes: 5

Views: 27511

Answers (4)

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)
}

Upvotes: 0

Artur INTECH
Artur INTECH

Reputation: 7266

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.

Upvotes: 0

KARTIK KUMAR
KARTIK KUMAR

Reputation: 9

<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

Upvotes: -2

adeneo
adeneo

Reputation: 318182

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;

Upvotes: 9

Related Questions