Last Updated: February 25, 2016
·
659
· Matt Slavicek

Using jQuery keycode enumerations

I found myself needing to detect if the user pressed the enter key quite a bit. I didn't like how there was a magic number for the enter key, so I hunted for an alternative.

jQuery UI to the rescue! The $.ui.keyCode object provides enumerations for the most common key codes.

In this example, I needed to ignore when the enter key was pressed in an autocomplete-enabled textbox.

$("#txtSearch").keypress(function (eventObject) {
    if (eventObject.which === $.ui.keyCode.ENTER) {
        return false;
    }
});

Much better!

For more details, visit http://api.jqueryui.com/jQuery.ui.keyCode