skip to Main Content

I’d like to take the content of a textarea and copy it inside a div element, preserving the html markup.

When I get the content of the textarea with jQuery using .val() and log it in the console it shows the markup (ie: linebreaks). But, when I try to update the div using .html() or .text() it strips links and linebreaks.

Here is my sample code:

function updateDiv() {
  var inpt = $('#textarea');
  console.log(inpt.val());
  if (inpt) {
    $('#div').text(inpt.val());
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form>
  <textarea id="textarea" style="height: 50px;"></textarea>
  <button type="button" onclick="updateDiv()">Submit</button>
</form>
<div style="height: 50px;"></div>
<div id="div" style="border: 1px solid gray; height: 50px;"></div>

Link to fiddle

I’ve tried variations of updating html, text, value, etc but cannot get it to preserve the line breaks or markup (ie: link).

2

Answers


  1. You can achive this by getting the HTML part directly and providing it as the inner text element. Hope it helps.

    function updateDiv() {
        let inpt = document.getElementById("textarea").value;
      console.log(inpt);
      if (inpt) {
        document.getElementById("div").innerHTML = inpt;
      }
    }
    <form >
      <textarea id="textarea" style="height: 50px;"></textarea>
      <button type="button" onclick="updateDiv()">Submit</button>
    </form>
    <div style="height: 50px;"></div>
    <div id="div" style="border: 1px solid gray; height: 50px;"></div>
    Login or Signup to reply.
  2. If you want HTML say HTML.
    Here I put this in the textarea <b>b thing</b><p>in paragraph</p> and that is the HTML that was placed in the target element.

    IF you want to change text line feeds that is an entirely different matter and you need to change those to appropriate HTML characters before you update the target element. WHAT you change them to is a matter of choice not specified in the OP if that is the real question here.

    function updateDiv() {
      var inpt = $('#textarea');
      console.log(inpt.val());
      if (inpt) {
        $('#div').html(inpt.val());
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <form>
      <textarea id="textarea" style="height: 50px;"></textarea>
      <button type="button" onclick="updateDiv()">Submit</button>
    </form>
    <div style="height: 50px;"></div>
    <div id="div" style="border: 1px solid gray; height: 50px;"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search