i'd go with something like this:
$(function () {
$(document).on('keyup keydown keypress', function (event) {
if (event.keyCode == 52 && event.shiftKey) {
alert('foo');
}
});
});
Question
The below method returns any key from A-Z and 0-9 and when I pressed shift key + 4 its returns the same code 52.
function keyUpEvent(e)//onkeyup event
{
var chr = String.fromCharCode(e.keyCode);//converts the keycode into a character
alert(chr);//alerts the character
}
But I need to show the $ or % when the respective key with combination of shift key is pressed.
Solution
i'd go with something like this:
$(function () {
$(document).on('keyup keydown keypress', function (event) {
if (event.keyCode == 52 && event.shiftKey) {
alert('foo');
}
});
});
OTHER TIPS
Key codes relate only to keys. $
is a character, achieved through two keys, Shift and 4. There is no key code explicitly for $
when using onkeydown
Edit: It was pointed out by Edward that onkeypress
uses key combinations, and does have keycode's for combinations. Learn something new every day :)
Here's some code, edited from the onkeydown
example provided by the MDN, to detect keypress keycodes.
Here's the fiddle updated to be Firefox-friendly, using help from this S.O. post. The JQuery solution works too, if you swing that way.
$ is equal to 36
.
JavaScript Event KeyCode Test Page
Here is same S.O thread
You cannot check for two key events at once. You can try e.shiftKey which tells you whether the shift key was being pressed when the event occurred. Try to check:
if(e.keyCode === 53 && e.shiftKey){}
also if you have a text field, than you can attach event on key enter and check for '%'.
https://developer.mozilla.org/en-US/docs/DOM/event.shiftKey
thanks to Marcel Korpel
In KeyDown
event of TextBox
, use:
if (e.Shift && e.KeyCode == Keys.4) {
//Your code here
}