5

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.

2
  • 1
    document.getElementById('taginput').value += i.innerHTML; 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. Commented Jul 20, 2017 at 13:33

4 Answers 4

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

-2
<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

Hi. To give a good answer please write your code in a snippet and explain what your code does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.