add text to a textarea without deleting the existing one

3

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

When it inserts this new text the old one is removed, I would like to be able to add the new text without removing the old one. Anyone have any tips / help?

    
asked by anonymous 14.05.2016 / 02:52

1 answer

0

When you use el.value = 'foo'; you will delete existing content and replace with foo . When you use el.value += 'foo'; you will keep the existing content and * add * foo .

Using += is a shortcut that actually does 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: link

    
14.05.2016 / 06:31