Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

javascript - Remove line break from textarea

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(/
/g, "");
    if (!util.isBlank(msg))
    {
        send(msg);
        $("#area").val("");
    }
    return false;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...