admin管理员组

文章数量:1417434

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

本文标签: javascriptclear HTML input after enter and prevent new lineStack Overflow