What is the keyCode for “$”?

放肆的年华 提交于 2019-12-30 17:57:55

问题


I am trying to disable all other characters from being entered in text input.

Since to get the $ you have to press the shift-key and the 4-key. I am not sure how you would get the keyCode for somthing like this?


回答1:


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.




回答2:


There is no onkeydown keycode, as previously said by ngmiceli

Although, onkeypress keycode exists and is equal to 36.

JavaScript Event KeyCode Test Page




回答3:


Then DONT use this way to solve your problem: since you cannot predict that every keyboard-layout will always have $-sign entered as shift+4.
You can still get keycode 4, and check if shift was pressed, but you could not be sure of this!!

Thus it would be better to simply replace all illegal characters in your fields (before you submit the data). Think: str.replace()
You could also check for your set of illegal characters on the onkeyup event of the input-box, effectively replacing all illegal characters as you type!
Like: onkeyup="this.value.replace(/[your illegal characters]/gi, '')"
That should do what you want.

Please note: you should NEVER trust browser-input, and should still filter this input in your receiving script!!!

Good Luck!!




回答4:


There is no key code for $, since it's not a valid key - it has to be accessed via some kind of shifter.

Usually, you would perform a check to see if the shifter was active, and the listen out for the keypress event on the relevant key. Something like this for a QWERTY layout in your instance:

var shiftPressed = false;

$(window).keydown(function(e) {  
    if(e.which == 16) { shiftPressed = true; }
    if(e.which == 52 && shiftPressed) 
    {  
        // Do whatever here...
    }
});

$(window).keyup(function(e) {  
    if(e.which == 16) { shiftPressed = false; }
});



回答5:


onkeypress - The Unicode CHARACTER code is: 36

onkeydown - The Unicode KEY code is: 52



来源:https://stackoverflow.com/questions/11868643/what-is-the-keycode-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!