Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get my textarea to preserve newlines when using jQuery and JSON?

I have a textarea for users to input comments and a button to submit using jQuery’s .post() and JSON:

$('#submit').click(function () {
    var comment = {};
    comment.Author = $("#author").val();
    comment.Email = $("#email").val();
    comment.WebSite = $("#url").val();
    comment.Body = $("#comment").val(); // textarea

    $.post('/ajax/comments', comment, parseComment, 'json');

But $("#comment").val() does not seem to preserve newlines (the input is losing newlines). How do I get this to work?

like image 992
Ray Avatar asked Jul 03 '10 23:07

Ray


People also ask

How do I preserve line breaks in textarea?

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. Enjoy!

How to get line break from textarea in JavaScript?

To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' . The combination of the \r and \n characters is used as a newline character.

How do you add text to a new line in textarea?

The text area tag defines a multi-line text input control. The size of a text area can be specified by the cols and rows attributes. By default, whenever we press “enter” or “shift+enter” it creates a new line in the text area.

Which character defines a new line in the textarea JS?

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.


2 Answers

A textarea does not insert <br> tags in a users input for line breaks, rather it simply includes the newline character \n.

This snippet will show an alert box when you click the button, which has the broken line.

<script type="text/javascript">
  $(document).ready(function(){
    $('#submit').click(function() { alert($('#comment').val()); })
  });
</script>

<textarea id='comment'></textarea>
<input type='submit' id='submit'/>

If you need to display these in the html page, you need to replace the \n with <br> yourself.

like image 61
Chadwick Avatar answered Oct 03 '22 06:10

Chadwick


use $('#comment').val().replace( /\n/g, '<br \\>' );.

like image 28
paicubes Avatar answered Oct 03 '22 06:10

paicubes