Remove line break from textarea

左心房为你撑大大i 提交于 2019-11-28 08:26:16

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;
});

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("");

        }

    }

} );

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