开发者

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

开发者 https://www.devze.com 2022-12-18 14:40 出处:网络
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 valu

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."

Here's the jQuery function I'm using:

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消