简体   繁体   English

jQuery:如何添加换行符以形成输入?

[英]jQuery: How can I add line break to form input?

I'm collecting information in a standard HTML form. 我正在以标准HTML表单收集信息。 I have, for example, <input type="text" name="UserName" id="name"/> . 例如,我有<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." 因此,如果用户输入“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. 任何帮助表示赞赏。

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/> 正如马克说,该换行符不会呈现在浏览器(或电子邮件客户端为此事)观看时一个换行符,这样反而增加了换行字符“\\ n”,你应该添加一个<br/>

$("#formID").submit(function () {
    $(":text").each(function () {
        var value = $(this).val();
        var newValue = value + '<br/>';
        $(this).val(newValue);
    });
})

Textbox doesn't holds "\\n" only textarea does. 文本框不包含“\\ n”只有textarea。 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. 您可以做的是将数据自己发布到控制器或将值存储在隐藏字段中并提交表单并读取服务器中的隐藏字段,如果您没有太多控制权,则将名称与隐藏字段匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM