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 mofifier 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
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 mofifier 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
