Page 1 of 1

jQuery - Add text in textarea without removing previous text

Posted: 31 Jan 2015, 15:38
by PloMar
How to add (append) text in textarea using jquery without removing previous text?
I have this code, but it only works for first time, when i change something in textarea and click again it does nothing.

Code: Select all

<form action="#" method="post">
  <textarea name="cnt1" id="cnt1"></textarea><br/>
  <input type="text" name="txt1" id="txt1" />
  <input type="button" value="Add" id="btn" />
</form>
<script>
$('#btn').on('click', function (){
   var insertText = $('#txt1').val();
   $('#cnt1').append(' '+ insertText);
});
</script>

jQuery - Add text in textarea without removing previous text

Posted: 31 Jan 2015, 15:48
by MarPlo
Inside the dom the value and text attributes are stored separately. When you use append the text is appended but the value is blanked because it is no longer consistent with the text. I believe your second call to $('#cnt1').va() is returning the blanked value, not the appended text.

Use val() to append the value of the textarea instead of append().
Get the current value from textarea, then concatenate the new text.

Code: Select all

<form action="#" method="post">
  <textarea name="cnt1" id="cnt1"></textarea><br/>
  <input type="text" name="txt1" id="txt1" />
  <input type="button" value="Add" id="btn" />
</form>
<script>
$('#btn').on('click', function (){
   var insertText = $('#txt1').val();
   $('#cnt1').val( $('#cnt1').val() +' '+ insertText);
});
</script>
Demo: