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.
asked Jul 20, 2017 at 13:27
Ajmal Rasi
951 gold badge1 silver badge7 bronze badges
4 Answers 4
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;
answered Jul 20, 2017 at 13:29
adeneo
319k29 gold badges410 silver badges392 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Dec 2, 2023 at 15:55
Artur INTECH
7,6233 gold badges49 silver badges41 bronze badges
Comments
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)
}
Artur INTECH
7,6233 gold badges49 silver badges41 bronze badges
Comments
<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
1 Comment
chrwahl
Hi. To give a good answer please write your code in a snippet and explain what your code does.
default
document.getElementById('taginput').value += i.innerHTML;