Javascript jQuery:如何在表单输入中添加换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2157739/
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
jQuery: How can I add line break to form input?
提问by theJBRU
I'm collecting information in a standard HTML form. I have, for example, <input type="text" name="UserName" id="name"/>. When the form is submitted, I want to add a line break to the value entered. So if the user entered "foo," the form would submit the value "foo\n."
我正在以标准的 HTML 表单收集信息。例如,我有<input type="text" name="UserName" id="name"/>。提交表单时,我想为输入的值添加换行符。因此,如果用户输入“foo”,表单将提交值“foo\n”。
Here's the jQuery function I'm using:
这是我正在使用的 jQuery 函数:
$("#formID").submit(function () {
$(":text").each(function () {
var value = $(this).val();
var newValue = value + " \n";
$(this).val(newValue);
});
});
When the form is submitted, however, the value assigned to the form field does not have the line break.
但是,提交表单时,分配给表单字段的值没有换行符。
My goal is for the line break to survive the output of the back-end form processing, which generates an email. Since I don't have control over the script that generates the mail, I'm trying to impose some formatting with what I can control.
我的目标是让换行符在后端表单处理的输出中存活下来,这会生成一封电子邮件。由于我无法控制生成邮件的脚本,因此我试图强加一些我可以控制的格式。
Any assistance is appreciated.
任何帮助表示赞赏。
采纳答案by Majid Fouladpour
I posted my previous answer before I saw your comment that the output is plain text. Now try this:
我在看到您的评论之前发布了我之前的答案,即输出是纯文本。现在试试这个:
$(document).ready(function() {
$("#formID").submit(function () {
$(":text").each(function () {
var value = $(this).val();
var myname = $(this).attr('name');
var newValue = value + " \n";
var hid = '<input type="hidden" name="' + myname + '" value="' + newValue + '"/>';
$(this).removeAttr('name');
$("#formID").append(hid);
});
});
});
Previous Answer
上一个答案
As Mark says, the line break character is not rendered as a line break when viewed in the browser (or email client for that matter), so instead of adding a line break character "\n", you should add a <br/>
正如 Mark 所说,在浏览器(或电子邮件客户端)中查看时,换行符不会呈现为换行符,因此不要添加换行符“\n”,而应添加一个 <br/>
$("#formID").submit(function () {
$(":text").each(function () {
var value = $(this).val();
var newValue = value + '<br/>';
$(this).val(newValue);
});
})
回答by Teja Kantamneni
Textbox doesn't holds "\n" only textarea does. What you can do is post the data yourself to the controller or store the values in hidden fields and submit the form and read the hidden fields in the server, if you don't have much control there match the names to the hidden fields.
文本框不包含 "\n" 只有 textarea 。您可以做的是自己将数据发布到控制器或将值存储在隐藏字段中,然后提交表单并读取服务器中的隐藏字段,如果您没有太多控制权,则将名称与隐藏字段匹配。

