The .val() of a textarea doesn't take new lines into account

ε祈祈猫儿з 提交于 2019-11-27 08:40:54

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

The forced new lines in textareas are \ns, 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/

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.

$( "#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/

Your newlines output perfectly, but HTML ignores newlines: it needs <br>.

Use a simple newline-to-br function like so:

function nl2br_js(myString) {
var regX = /\n/gi ;

s = new String(myString);
s = s.replace(regX, "<br /> \n");
return s;
}

$( "#watched_textarea" ).keyup( function() {
       $( "#output_div" ).html( nl2br_js($( this ).val()) );
    }); 

jsfiddle here: http://jsfiddle.net/r5KPe/

Code from here: http://bytes.com/topic/javascript/answers/150396-replace-all-newlines-br-tags

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');

There is a easy solution: make the container with pre tag.

        <textarea id="watched_textarea" rows="10" cols="45">test </textarea>
        <pre class="default prettyprint prettyprinted"><code ><span class="pln" id="output_div">fdfdf</span></code></pre>
        <script>
        $("#watched_textarea").keyup(function() {
            $("#output_div").html($(this).val());
        });
        </script>
<?php 

//$rsquery[0] is array result from my database query
//$rsquery[0] = 1.1st Procedure \n2.2nd Procedure
//txtRisks is a textarea

//sample1
function nl2br2($string) {
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
return $string;
}

//sample2
function nl2br2($string) {
$string = str_replace(array("\r\n", "\r", "\n"), "\\n", $string);
return $string;
}

echo "$('#txtRisks').val('".nl2br2($rsquery[0])."')";

?> 

PHP Manual link

I have found a more convenient method using jquery.

samplecode

HTML

    <textarea></textarea>
    <div></div>
    <button>Encode</button>

JS

$('button').click(function() {

    var encoded = $('<label>').text($('textarea').val()).html();//the label element can be replaced by any element like div, span or else

    $('div').html(encoded.replace(/\n/g,'<br/>'))
});

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!