The .val()
property of an item in jQuery for a doesn\'t seem to work with new lines. I need this function as the text-area is mean
I had tried to set the textarea value with jquery in laravel blade template, but the code was breaking because the variable had new lines in it.
my code snippet was
$("#textarea_id").val("{{ $php_variable }}");
I solved my problem by changing my code snippet like below.
$("#textarea_id").val("{{ str_replace(array('\r', '\n', '\n\n'), '\n', $php_variable }}");
if any of you are facing this problem may take benifit from this.
It's a CSS problem, not a JavaScript problem. HTML collapses white space by default — this includes ignoring newlines.
Add white-space: pre-wrap to the output div. http://jsfiddle.net/mattball/5wdzH/
This is supported in all modern browsers: https://caniuse.com/#feat=css3-tabsize
In the case that
you are NOT displaying the .val() of the textarea in another page (for example, submit form to Servlet and forward to another JSP).
using the .val() of the textarea as part of a URL encoding (e.g. a mailto: with body as textarea contents) within Javascript/JQuery
then, you need to URLEncode the textarea description as follows :
var mailText = $('#mailbody').val().replace(/(\r\n|\n|\r)/gm, '%0D%0A');
The forced new lines in textareas are \n
s, other HTML tags than textarea will ignore these. You have to use <br />
to force new lines at those elements.
I suggest you use JavaScript to fix that rather than CSS as you already rely on JavaScript.
$( "#watched_textarea" ).keyup( function() {
$( "#output_div" ).html( $( this ).val().replace(/\n/g, '<br />') );
});
You can find the updated version here: http://jsfiddle.net/GbjTy/2/
$( "#watched_textarea" ).keyup( function() {
$( "#output_div" ).html( $( this ).val().replace(/[\r\n]/g, "<br />") );
});
You need to replace the new-line characters with <br>
tags for HTML output.
Here is a demo: http://jsfiddle.net/GbjTy/3/
Try something like this:
$( "#watched_textarea" ).keyup( function() {
$( "#output_div" ).html( $( this ).val().replace('\n', '<br/>') );
});
In HTML, whitespace gets ignored by default.
You could also change your <div>
tag into a <pre>
tag:
<pre id="output_div"></pre>
And that would work as well.