Write elements to textarea using jQuery

47

Solution 1

Try this:

$('div#Thelper4_container textarea').append(document.createTextNode(x));

Please note the 'document.createTextNode'.

Solution 2

Use val instead of append. Append is for non-form field container elements

Although you CAN append to a textarea, when you append, you append HTML and not text.

Also you have too many </span>s and spans do not have values. I changed to data-value

Lastly I filter empty lines

const $txtarea = $('#Thelper2_container textarea');
const $output =  $('#Thelper4_container textarea');
const splitLines = val => val
  .split('\n')
  .filter(line => line.trim() !== "") // drop empty lines
  .map((line,i) => `<span class="textToSelect" data-value="${i+1}">${line.trim()}</span>`)
  .join("\n");

$(function() {
  $output.val(splitLines($txtarea.val()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Thelper2_container">
  <textarea rows="5" cols="100">Line 1
Line 2
</textarea>
</div>
<div id="Thelper4_container">
  <textarea rows="5" cols="100"></textarea>
</div>

Share:
47

Related videos on Youtube

Ballazx
Author by

Ballazx

Updated on December 31, 2022

Comments

  • Ballazx
    Ballazx over 1 year

    I want to get a text from a and add some attributes to the text and show it in another when a button is pressed.

    Here is a part of my code - If I use console.log() the correct text will be logged, but the append(x) only writes the option[i] value without any HTML codes.

    What should be the solution here?

    var options;
    $(function() {
      options = $('div#Thelper2_container textarea').val().split('\n');
      $.fillTextArea();
    
    });
    
    $.fillTextArea = function() {
      for (let i = 0; i < options.length; i++) {
        var y = i + 1;
        var x = String('<span class="textToSelect" value="' + y + '"></span>' + options[i] + '</span>\n');
        $('div#Thelper4_container textarea').append(x);
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="Thelper2_container">
      <textarea rows="5" cols="100">Line 1
    Line 2
    </textarea>
    </div>
    <div id="Thelper4_container">
      <textarea rows="5" cols="100"></textarea>
    </div>

    • mplungjan
      mplungjan over 2 years
      use val instead of append
    • Ballazx
      Ballazx over 2 years
      in this way the previous values will be overwritten, so only the text of the last iteration will be in the textarea
    • mplungjan
      mplungjan over 2 years
      See my UPDATED answer to see what I mean
  • mplungjan
    mplungjan over 2 years
    This is such a inefficient solution. You basically append html you convert to text before appending. Also it does not remove empty lines
  • SusanCalvin
    SusanCalvin over 2 years
    Yep, the String() before is useless. My solution maybe is not elegant.