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
4 Answers
Reset to default 9You 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