Question:
I have a textarea ( id='text'), where 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 he 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. Does anyone have any tips/help?
Answer:
When you use el.value = 'foo';
you will delete the existing content and replace it with foo
.
When you use el.value += 'foo';
you will keep the existing content and **add* foo
.
Using +=
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>