Home > Net >  jQuery - Append dynamic content into textarea
jQuery - Append dynamic content into textarea

Time:11-02

I have several elements that were dynamically added to my web page and now I'm trying to append them to textarea, but I keep getting only the last element to show up.

I figured I need to use val() instead of append(), but with val() I only get last option that was stated.

Can someone help me out? I'm trying to include all rows in the textarea.

I've recreated my problem in a snippet bellow.

function getDetails() {
  // Clear content
  $("#save-content").val('');

  // First headline
  $("#save-content").val("First group: \n");

  // Content from first group
  $(".first-item .row").each(function(){
    var firstGroupName = $(this).find(".name").text();
    var firstGroupSurname = $(this).find(".surname").text();

    $("#save-content").val(firstGroupName   " "   firstGroupSurname    "\n");
  });

  // Second headline
  $("#save-content").val("Second group: \n");

  // Content from second group
  $(".second-item .row").each(function(){
    var secondGroupName = $(this).find(".name").text();
    var secondGroupSurname = $(this).find(".surname").text();

    $("#save-content").val(secondGroupName   " "   secondGroupSurname    "\n");
  });

  // Third headline
  $("#save-content").val("Third group: \n");

  // Content from third group
  $(".third-item .row").each(function(){
    var thirdGroupName = $(this).find(".name").text();
    var thirdGroupSurname = $(this).find(".surname").text();

    $("#save-content").val(thirdGroupName   " "   thirdGroupSurname    "\n");
  });
}


$('button').on('click', function() {
  getDetails();
});
.row>div {
  display: inline-block;
}

button {
  display: block;
  margin: 10px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >

  <div >
    <div >
      <div >Penelope</div>
      <div >Smith</div>
    </div>
    <div >
      <div >Jane</div>
      <div >Dalton</div>
    </div>
  </div>

  <div >
    <div >
      <div >Kate</div>
      <div >Davidson</div>
    </div>
  </div>

  <div >
    <div >
      <div >David</div>
      <div >Peters</div>
    </div>
    <div >
      <div >Brad</div>
      <div >Lucas</div>
    </div>
  </div>

</div>

<button>Import</button>

<textarea id="save-content" rows="5"></textarea>

CodePudding user response:

You can add the val when settings the val when you want to append.

For example:

$('#save-content').val($('#save-content').val()   yourContentHere);
  • Related