How to get a text box to save newlines when using jQuery and JSON?

I have a text box for inputting comments and buttons for submitting using jQuerys .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 store newline characters (input loses newline characters). How can I make this work?

+6
jquery line-breaks textarea jquery-post
source share
4 answers

The text box does not insert <br> tags in user input for line breaks, but simply includes the newline character \n .

This snippet displays a warning window when you click the polyline button.

 <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 them on the html page, you need to replace \n with <br> yourself.

+5
source share

Does he lose new lines? See this post , maybe?

+2
source share

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

+1
source share

You just need to use encodeURIComponent by the value of the text field and send it to the server .. when you print it. You can use nl2br if php for example

+1
source share

All Articles