Reputation: 7009
If a character is entered through keyboard using the SHIFT key then the keydown
or keyup
event only can trace the keyCode
of SHIFT key i.e. 16.
Then how to trace the keyCode
of the character actually printed?
I am using the following code-
onkeyup='alert(event.keyCode)';// Always shows a message 16(keyCode of SHIFT) irrespective of the actual character
or
onkeydown='alert(event.keyCode)';// Always shows a message 16(keyCode of SHIFT) irrespective of the actual character
Then how to get keyCode
of the actual character printed???
Upvotes: 19
Views: 46619
Reputation: 653
As an alternative solution you can create a new event listener of keydown and create an if statement which holds e.shiftKey
as boolean. If it returns true, nest a new if statement of e.which
which will only return true for symbols and not for numbers.
input.addEventListener('keydown', e => {
if(e.shiftKey)
if(e.which == 52){
// will only return the value of dollar sign ($) not a number 4
}
})
reference: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/shiftKey
Upvotes: 2
Reputation: 8715
You can see the property shiftKey
of the passed event object.
Take a look at this Fiddle
When you press Shift you can see the keyCode of it and shiftKey
property true
. Press any button together, i.e. Shift+A and the console outputs:
65
true
Which is the code of A and shiftKey
property again.
Upvotes: 29
Reputation: 7009
Got the solution
I had to use onKeyPress
event which does not treat SHIFT as keypress but the resultant character instead.
Hence I can get the keyCode
of the actual resultant character using onKeyPress
event.
Syntax:
onkeypress='alert(event.keyCode)';
Now If I press SHIFT+A it prompts the keyCode of A i.e. 65.
Upvotes: 12