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

纵饮孤独 提交于 2019-12-17 09:45:17

问题


The .val() property of an item in jQuery for a <textarea> doesn't seem to work with new lines. I need this function as the text-area is meant to recognize the enter key and display it as a preview, with the new line in tact.

However, what happens is shown in this fiddle: http://jsfiddle.net/GbjTy/1/. The text is displayed, but not in a new line.

How can I achieve the preview to include new lines, and I know it is possible, because it does this in the Stack Overflow Post Question preview.

Thanks.

P.S I have seen other links on SO relating to this, but they all say get the End User to use some code, which is not an ideal method for me. How can I achieve this without the End User writing any specific code, like here on SO Question Preview, where the Enter works as it should in the preview.


回答1:


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




回答2:


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/




回答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.




回答4:


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



回答5:


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




回答6:


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




回答7:


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>



回答8:


<?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




回答9:


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



回答10:


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.



来源:https://stackoverflow.com/questions/8481025/the-val-of-a-textarea-doesnt-take-new-lines-into-account

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