jQuery textarea 的 .val() 不考虑新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8481025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The .val() of a textarea doesn't take new lines into account
提问by H Bellamy
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.
.val()
jQuery 中项目的属性 a<textarea>
似乎不适用于新行。我需要此功能,因为文本区域旨在识别回车键并将其显示为预览,新行保持原样。
However, what happens is shown in this fiddle: http://jsfiddle.net/GbjTy/1/. The text is displayed, but not in a new line.
但是,这个小提琴显示了发生的情况:http: //jsfiddle.net/GbjTy/1/。文本会显示,但不会在新行中显示。
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.
我怎样才能实现包含新行的预览,我知道这是可能的,因为它在 Stack Overflow Post Question 预览中做到了这一点。
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.
PS 我在 SO 上看到了与此相关的其他链接,但他们都说让最终用户使用一些代码,这对我来说不是一个理想的方法。如何在没有最终用户编写任何特定代码的情况下实现这一点,例如在 SO Question Preview 中,Enter 在预览中正常工作。
回答by Matt Ball
It's a CSS problem, not a JavaScript problem. HTML collapses white space by default — this includes ignoring newlines.
这是一个 CSS 问题,而不是一个 JavaScript 问题。HTML 默认折叠空白——这包括忽略换行符。
Add white-space: pre-wrap
to the output div. http://jsfiddle.net/mattball/5wdzH/
添加white-space: pre-wrap
到输出div。http://jsfiddle.net/mattball/5wdzH/
This is supported in all modern browsers: https://caniuse.com/#feat=css3-tabsize
所有现代浏览器都支持此功能:https: //caniuse.com/#feat=css3-tabsize
回答by js-coder
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.
textareas 中\n
的强制换行是s,除 textarea 之外的其他 HTML 标签将忽略这些。您必须使用<br />
在这些元素上强制换行。
I suggest you use JavaScript to fix that rather than CSS as you already rely on JavaScript.
我建议你使用 JavaScript 来解决这个问题,而不是 CSS,因为你已经依赖 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/
你可以在这里找到更新的版本:http: //jsfiddle.net/GbjTy/2/
回答by Mike Christensen
Try something like this:
尝试这样的事情:
$( "#watched_textarea" ).keyup( function() {
$( "#output_div" ).html( $( this ).val().replace('\n', '<br/>') );
});
In HTML, whitespace gets ignored by default.
在 HTML 中,默认情况下会忽略空格。
You could also change your <div>
tag into a <pre>
tag:
您还可以将<div>
标签更改为<pre>
标签:
<pre id="output_div"></pre>
And that would work as well.
这也能奏效。
回答by RuntimeException
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
您没有在另一个页面中显示 textarea 的 .val() (例如,将表单提交到 Servlet 并转发到另一个 JSP)。
在 Javascript/JQuery 中使用 textarea 的 .val() 作为 URL 编码的一部分(例如 mailto: with body as textarea 内容)
then, you need to URLEncode the textarea description as follows :
然后,您需要对 textarea 描述进行 URLEncode,如下所示:
var mailText = $('#mailbody').val().replace(/(\r\n|\n|\r)/gm, '%0D%0A');
回答by Jasper
$( "#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.
您需要用<br>
HTML 输出的标签替换换行符。
Here is a demo: http://jsfiddle.net/GbjTy/3/
这是一个演示:http: //jsfiddle.net/GbjTy/3/
回答by Nanne
Your newlines output perfectly, but HTML ignores newlines: it needs <br>
.
您的换行符输出完美,但 HTML 忽略换行符:它需要<br>
.
Use a simple newline-to-br function like so:
使用一个简单的 newline-to-br 函数,如下所示:
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/
jsfiddle在这里:http: //jsfiddle.net/r5KPe/
Code from here: http://bytes.com/topic/javascript/answers/150396-replace-all-newlines-br-tags
来自这里的代码:http: //bytes.com/topic/javascript/answers/150396-replace-all-newlines-br-tags
回答by Sanjib Debnath
There is a easy solution: make the container with pre tag.
有一个简单的解决方案:使用 pre 标记制作容器。
<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>
回答by Nithin Chandran
I have found a more convenient method using jquery.
我找到了一种更方便的使用 jquery 的方法。
samplecode
示例代码
HTML
HTML
<textarea></textarea>
<div></div>
<button>Encode</button>
JS
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/>'))
});
回答by Sunil Kumar
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.
我曾尝试在 laravel 刀片模板中使用 jquery 设置 textarea 值,但代码中断了,因为变量中有新行。
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.
如果你们中的任何人面临这个问题,可能会从中受益。
回答by crazyivan
<?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])."')";
?>