Reputation: 4608
How do I restrict a keydown event to only take effect when a character is pressed? I'd like to skip the code when a non-character is pressed on the keyboard, e.g. home button, end button.
I know I could target those buttons with e.which == someNumber
but is there a better way to do it? Writing a condition for each non-character button doesn't seem like a good idea.
Thank you!
Upvotes: 2
Views: 1390
Reputation: 11
My implementation looks like one small check for the number of characters in E.key. Only symbolic buttons and gaps are called one symbol in this key, the rest of the type Escape, Enter, etc. They have more characters in the name. That's why:
if(e.key.length==1){
}
It may also be necessary to take into account the removal of symbols, then:
if(e.key.length==1||e.key=="Backspace"||e.key=="Delete"){
}
Later I was faced with the fact that in the field, combinations of fast keys can be used, which in some case should cause changes in the fields and in some, I did not make the next design (I want to note that E.CODE is used to combine the keys, since It indicates precisely the button without taking into account its register):
if(e.key.length==1||e.key=="Backspace"||e.key=="Delete"){
if((e.ctrlKey&&e.code=="KeyA")
||(e.ctrlKey&&e.code=="KeyC")
){return;}
//Here is the code that occurs if there are any changes in Input
}
I don’t know how to resolve the issue with the moment when a person with the mouse presses the right button and presses “delete”, but this question will seem to go to check the timer during the focus on the field, for checking the Change event
Upvotes: 1
Reputation: 10573
try this
$(function () {
$(document).on('keydown', function (event) {
if (event.keyCode == yourkeycode) {
//stuff
}
});
});
Upvotes: 1
Reputation: 4112
You have to implement some form of range checking. Pick the range that takes the least amount of coding. What would you characterize as a character? Would it be everything between 32 and 125? Check out the range you're interested in on an ascii table.
Upvotes: 1