Harts
Harts

Reputation: 4093

jQuery empty out text area then append data does not work

I have a textarea, I am supposed to empty out all the data, then append a new data. I tried something like this, but it always ended up empty data. The textarea is just a standard html input:

<textarea name="mytextarea" id="mytextarea" rows="8" 
class="form-control" readonly="readonly">myOldData</textarea>

//This resulting in empty data
$('#mytextarea').val('');
$('#mytextarea').append("myData1");
$('#mytextarea').append("myData2");

but if:

//This resulting in just myData1
$('#mytextarea').val('');
$('#mytextarea').val("myData1");
$('#mytextarea').append("myData2");

case 3 is if I don't need to empty out data and just append that will work fine:

//This resulting in just myData1myData2
$('#mytextarea').val("myData1");
$('#mytextarea').append("myData2");

What is happening here? How can I empty out the data first, then append some new data?

Upvotes: 0

Views: 1468

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388316

I think append is the wrong choice... to set the value of an input element you need to use .val().

So I would suggest you create a concatenated string then set that as the textarea's value.

Another choice is to create a plugin like

(function($) {
  $.fn.appendVal = function(value) {
    console.log(this, this.val)
    return this.val(function(i, val) {
      return val + value
    });
  }
})(jQuery);

jQuery(function($) {
  //This resulting in empty data
  $('#mytextarea').val('');
  $('#mytextarea').val("myData1");
  $('#mytextarea').val(function(i, val) {
    return val + "myData2"
  });
  $('#mytextarea').appendVal('myData3')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea name="mytextarea" id="mytextarea" rows="8" class="form-control" readonly="readonly">myOldData</textarea>

Upvotes: 1

rdubya
rdubya

Reputation: 2916

If you are just attempting to set the value. I would build out the string you want to put in the text area then set it all at once.

I.E.

var newString = 'myData1';
newString += 'myData2';

$('#mytextarea').val(newString);

.append() is used for appending DOM elements to a parent DOM element

Upvotes: 1

Vipul Hadiya
Vipul Hadiya

Reputation: 882

How can you append data to textarea? Append method should be used with container tags like div, span, ul, ol. Use .val() to set new data in textarea.

If you want to append something than append it to parent of your #myData textarea. It will serve your purpose.

Upvotes: 1

Related Questions