Remove line break from textarea

假如想象 提交于 2019-11-27 02:12:31

问题


I have a textarea like this:

<textarea tabindex="1" maxlength='2000' id="area"></textarea>

I watch this textarea with jquery:

$("#area").keypress(function (e) {
    if (e.keyCode != 13) return;
    var msg = $("#area").val().replace("\n", "");
    if (!util.isBlank(msg))
    {
        send(msg);
        $("#area").val("");
    }
});

send() submits the message to the server if the return key was pressed and if the message is not blank or only containing line spaces.

The problem: After sending the message, the textarea is not cleared. On the first page load, the textarea is empty. Once a message was submitted, there is one blank line in the textarea and I don't know how to get rid of it.


回答1:


The problem is that the Enter keypress is not being suppressed and is doing its usual browser behaviour (i.e. adding a line break). Add return false to the end of your keypress handler to prevent this.

$("#area").keypress(function (e) {
    if (e.keyCode != 13) return;
    var msg = $("#area").val().replace(/\n/g, "");
    if (!util.isBlank(msg))
    {
        send(msg);
        $("#area").val("");
    }
    return false;
});



回答2:


Thomas, the e.preventDefault(); would need to be wrapped inside a conditional applying it only to the enter key.

// Restrict ENTER.
if (e.keyCode == '13') { e.preventDefault(); }

The whole function would look something like this (with commenting):

// Key Press Listener Attachment for #area.
$("#area").keypress( function (event) {

    // If the key code is not associated with the ENTER key...
    if (event.keyCode != 13) {

        // ...exit the function.
        return false;

    } else {

        // Otherwise prevent the default event.
        event.preventDefault();

        // Get the message value, stripping any newline characters.
        var msg = $("#area").val().replace("\n", "");

        // If the message is not blank now...
        if (!util.isBlank(msg)) {

            // ...send the message.
            send(msg);

            // Clear the text area.
            $("#area").val("");

        }

    }

} );



回答3:


You'll want to use the event.preventDefault() function to prevent the default event action from happening, in this case adding the enter character:

$("#area").keypress(function (e) {
    e.preventDefault();
    if (e.keyCode != 13) return;
    var msg = $("#area").val().replace("\n", "");
    if (!util.isBlank(msg))
    {
        send(msg);
        $("#area").val("");
    }
});


来源:https://stackoverflow.com/questions/4429757/remove-line-break-from-textarea

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