Michael Fitzgerald
Michael Fitzgerald

Reputation: 37

Using .val to populate textarea

I'm currently trying to populate a text area with values from multiple inputs as they are typed, my problem is everytime I go to a new input, it clears the previous information from the text area and adds the new, is there anyway I can keep the information from previous fields and also add new info.

html

<input type="text" name="fname" ><br>
<input type="text" name="lname"><br>

<textarea type="text" id="content"></textarea><br>

jQuery

  $("input").keyup(function () {
  var value = $(this).val();
  $("#content").text(value);
  }).keyup();

Codepen http://codepen.io/michael52/pen/uzeqs

Upvotes: 0

Views: 265

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

You'll need to append the new content, rather than replacing the old content:

$("#content").text(function(_, oldText) {
    return oldText + value;
});

Upvotes: 1

mrks
mrks

Reputation: 8343

Why don't you build the textarea's content based on the other two boxes, not the old value of the textarea:

<input type="text" name="fname" id="fname"><br>
<input type="text" name="lname" id="lname"><br>

<textarea type="text" id="content"></textarea><br>

JS:

$("input").keyup(function () {
  var value = $('#fname').val() + ' ' + $('#lname').val();
  $("#content").text(value);
}).keyup();

Upvotes: 4

Related Questions