Save multiline text from text box

I have a form containing a <textarea>....</textarea> field. after saving the text, it displays the result in a different form, but in <p>...</p>

the problem is that it shows all the lines connected together as one line

When I go into the edit box, the line appears correctly (multi-line)

how to show the whole line specified in <textarea>....</textarea> ?

+5
source share
3 answers

There are two ways to solve this problem -

  • Using Tags <br>

    You need to convert newlines to <br> tags when displaying data in your <p> paragraph. Something in the following lines will help -

     var value = $('.textareaClass').val(); $('.paragraphClass').html('<p>'+(value.replace(/\r?\n/g,'<br/>'))+'</p>'); 
  • Using CSS Rules

    Another easy way to do this is to use CSS, in which you just need to add the white-space: pre-wrap rule to the <p> class. For example, if your paragraph has a text-content class, you just need to do -

     .text-content { white-space: pre-wrap; } 

    DEMO: JSFiddle

Hope this helps!

+4
source

You need to replace newline <br> to provide a new line in html

 $('#text').on('input', function() { $('#res').html(this.value.replace(/\r?\n/g, '<br>')); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <textarea id=text></textarea> <div id=res></div> 

Or you need to wrap each line after a new line in p tag

 $('#text').on('input', function() { $('#res').html('<pr>' + this.value.split(/\r?\n/).join('</p><p>') + '</p>'); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <textarea id=text></textarea> <div id=res></div> 
+2
source

Use <pre> instead of <p> and let it have the same <textarea> width. Additional options added to copy wrapper and scroll behavior:

 function test(){ var thetarget = document.getElementById("b"); thetarget.innerHTML = document.getElementById("a").value; thetarget.scrollTop = thetarget.scrollHeight; } 
 body { background: lavender; } textarea, pre { width: 200px; height: 176px; white-space: -moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word; float: left; margin-left: 10px; margin-top: 0; overflow-y: auto; } 
 <textarea id=a oninput="test()"></textarea><pre id=b></pre> 
+1
source

Source: https://habr.com/ru/post/1245754/


All Articles