Check for modifier keys when using jQuery's .keyPress()

I was developing a simple chat log for a website, and I wanted the user to be able to submit a message when they hit the "enter" key but not if the "alt/option" key is being pressed. If the "alt/option" key is being pressed while the user hits the "enter" key, I want a carriage return to be entered in the chat field instead.

The jQuery .keyPress() doc page is a bit light on details, so here's how you can check for modifier keys with the .keyPress() event handler:

$('textarea#chat_message').keypress(function(e) {
    if (e.which == 13) { // enter key was pressed
        if (e.altKey) { // alt/option key is down
            // don't submit
        }
        else {
            // submit
        }
    }
});

The modifier keys you can test for are:

altKey - alt/option key
ctrlKey - control key
shiftKey - shift key
metaKey - control key on PCs, control and/or command key on Macs

florin Nov 24, 2010

Thanks. I needed that.

levu Dec 22, 2010

thx, why isn't this in official jQuery documentation? :)

Guillaume Feb 23, 2011

I think this only works in Firefox, but not in Chrome nor IE...

Jamie Tibbetts Feb 23, 2011

You're right, Guillaume. It does only work in Safari and Firefox.

In IE, alt-enter resizes the window. :(

jajaja Dec 4, 2012

@levu Because "eventhandler" is a javascript object, so altkey should be in Javascript docs

Artem Russakovskii Mar 11, 2013

Exactly what I was looking for when figuring out how to not have Firefox fire on "Ctrl-C" when I am only expecting it to fire on "c".

Leave a Comment