Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save multi-line text from textarea

Tags:

html

jquery

css

I have a form which contains a <textarea>....</textarea> field. after saving the text it shows the result in another form but in paragraph <p>...</p>

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

when I go to edit field, the line are presented correctly (multi-lines)

how to show all line as entered in <textarea>....</textarea>?

like image 585
Abdallah Sabri Avatar asked Mar 25 '16 07:03

Abdallah Sabri


People also ask

How do I preserve line breaks in textarea?

Preserve Newlines, Line Breaks, and Whitespace in HTML If you want your text to overflow the parent's boundaries, you should use pre as your CSS whitespace property. Using white-space: pre wraps still preserves newlines and spaces.

How do you store line breaks in database?

Insert SQL carriage return and line feed in a string In SQL Server, we can use the CHAR function with ASCII number code. We can use the following ASCII codes in SQL Server: Char(10) – New Line / Line Break. Char(13) – Carriage Return.

Which choice will place a multiline text input field on the page?

To create a multi-line text input, use the HTML <textarea> tag. You can set the size of a text area using the cols and rows attributes. It is used within a form, to allow users to input text over multiple rows.


2 Answers

There are two ways to solve this problem-

  1. Using <br> tags

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

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

    Another simpler way to do this is by using CSS, in which, you simply have to add the rule white-space: pre-wrap to your <p> class. For example, if your paragraph has class text-content then you simply have to do-

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

    DEMO: JSFiddle

Hope this helps!

like image 124
Shekhar Chikara Avatar answered Oct 02 '22 23:10

Shekhar Chikara


You need to replace newline with <br> to provide 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 string after newline 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>
like image 38
Pranav C Balan Avatar answered Oct 02 '22 23:10

Pranav C Balan