Ray
Ray

Reputation: 12441

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?

Upvotes: 7

Views: 16891

Answers (4)

estinamir
estinamir

Reputation: 503

The only solution I've found is to pass textarea data separately outside of json. Inside json it needs to be escaped like \n but this looses the new lines when you reload it from db.

So for json purposes I escape it to avoid the parsing error. Also I save this textarea field separately as it is by another (non json parsed) variable.

Upvotes: 0

Julius Koronci
Julius Koronci

Reputation: 417

You just need to use encodeURIComponent on the value of the textarea and send it to the server..when you print it out..you can use nl2br if PHP for instance

Upvotes: 1

paicubes
paicubes

Reputation: 151

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

Upvotes: 3

Chadwick
Chadwick

Reputation: 12663

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.

Upvotes: 6

Related Questions