add text to a textarea without deleting existing text

Asked

Viewed 3,327 times

3

I have a textarea ( id='text'), which the user type his text freely (so far so good), at the end he clicks on a button that inserts a signature example: "Typed by so-and-so".

When it inserts this new text the old one is removed, I wish I could add the new text without removing the old one. Someone has some hint/help?

  • You can put the code you’re using?

  • Document.getElementById('text'). value; - :/

  • @Moreirasouza, could [Dit] your post and add your whole code, I believe the solution would be just a concatenation operator += in the right place ;)

  • <textarea id="text"> text that has to stay tbm </textarea> the problem is that I have no idea how to do, I try to do so. Document.getElementById(text). value+"phrase that tbm will stay"; and not sure... miss the errors I’m by cell phone

1 answer

1


When you use el.value = 'foo'; you’re gonna erase the existing content and replace for foo.
When you use el.value += 'foo'; you’re gonna keep up existing content and **add* foo.

Use += is a shortcut that in practice makes el.value = el.value + 'foo';

var textarea = document.querySelector('textarea');
var button = document.querySelector('button');
var assinatura = '\n\nCumprimentos,\nSuper heroi.'

button.addEventListener('click', function() {
  textarea.value += assinatura;
});
button {
    display: block;
}
textarea {
	height: 100px;
	width: 200px;
}
<textarea name="texto" id="texto"></textarea>
<button type="button">Assinar</button>

jsFiddle: https://jsfiddle.net/tbn7y4L7/

  • 1

    Thank you Sergio, it worked perfectly !! What I really lack is paying more attention to the details, and deepening the logic, because from what I understood it was something simple. addeventlistener I’m still trying to understand a little, always forget how to use it. I appreciate your help and the others.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.