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?
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!
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.
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.
Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.
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.
use $('#comment').val().replace( /\n/g, '<br \\>' );
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With