javascript - clear HTML input after enter and prevent new line - Stack Overflow

I want to submit the value of a textbox when the user presses enter, and finally clear the input. I tri

I want to submit the value of a textbox when the user presses enter, and finally clear the input. I tried this code:

input.keydown(function(e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        $(this).val('');
        ...
    }

The input field's text clears as it's supposed to, but after clearing, the newline is still entered in the input. This means that the user has to remove this newline after sending a message every time. Is there a way to prevent this newline from appearing, aside from hack-ish methods like setting an interval?

I want to submit the value of a textbox when the user presses enter, and finally clear the input. I tried this code:

input.keydown(function(e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        $(this).val('');
        ...
    }

The input field's text clears as it's supposed to, but after clearing, the newline is still entered in the input. This means that the user has to remove this newline after sending a message every time. Is there a way to prevent this newline from appearing, aside from hack-ish methods like setting an interval?

Share Improve this question edited Apr 23, 2013 at 10:25 George 36.8k9 gold badges69 silver badges109 bronze badges asked Apr 23, 2013 at 10:14 Guido PassageGuido Passage 1,0501 gold badge10 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Just return false when enter is pressed:

input.keydown(function(e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        $(this).val('');
        return false;
    }
}

Of course this means that your end-user won't be able to actually create a new line. In this case I usually have a boolean variable that changes when the shift key is pressed/released. So if shift is down, don't submit, make a new line.

If you're submitting with AJAX you can clear the input after collecting the data for the AJAX payload.

If you're doing a regular page changing submit, you could add an onbeforeunload callback that clears the input.

Return false in the keydown event, this prevents the event from bubbling down so it never actually does anything to the textbox.

input.keydown(function(e) {
    if (e.keyCode == 13) {
        $(this).val('');
        e.preventDefault();
        return false;
    }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745257443a4619041.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信