JQuery: Keyup, how do I prevent the default behavior of the arrow (up & down) and enter key?

user317005 picture user317005 · Jun 2, 2011 · Viewed 67.9k times · Source

JavaScript (JQuery)

$('input').keyup(function(e)
{
    var code = e.keyCode ? e.keyCode : e.which;

    switch(code)
    {
        case 38:
        break;

        case 40:
        break;

        case 13:
        break;

        default:
        return;
     }
 });

HTML

<form method="post" action="/">
<input type="text" name="text" />
<button type="submit">Submit</button>
</form>

I have 2 problems:

1) The caret shouldn't move when I hit the up arrow key.

For example, in Chrome when I hit the up-key it moves the caret to the left. But I only have this problem in Chrome. It works fine in FF.

2) When I hit the enter key, I don't want the form to be submitted.

BTW, I want to get this to work with keyup and not keypress.

I'd appreciate any ideas. Thanks.

Answer

no.good.at.coding picture no.good.at.coding · Jun 2, 2011

I don't think you can preventDefault() (which is what you'd need to use to stop the browser from performing the default action for a key) on the keyup event - it is fired after the default event has already occurred. See this page for more.

If you can, consider using the keydown instead.

As for stopping the form from submitting, you could bind to the submit event and return false; when the submit was not triggered by the submit button (see jQuery: how to get which button was clicked upon form submission? for how to determine this).

On the other hand, you could also bind to keypress for the form and when Enter is pressed, cancel submission the same way (untested code):

$('form').keypress(function(e){
    if(e.which === 13){
        return false;
    }
});