What is the keyCode for “$”?

前端 未结 5 1917
萌比男神i
萌比男神i 2021-01-18 06:07

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

相关标签:
5条回答
  • 2021-01-18 06:33

    onkeypress - The Unicode CHARACTER code is: 36

    onkeydown - The Unicode KEY code is: 52

    0 讨论(0)
  • 2021-01-18 06:35

    There is no onkeydown keycode, as previously said by ngmiceli

    Although, onkeypress keycode exists and is equal to 36.

    JavaScript Event KeyCode Test Page

    0 讨论(0)
  • 2021-01-18 06:36

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

    0 讨论(0)
  • 2021-01-18 06:36

    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; }
    });
    
    0 讨论(0)
  • 2021-01-18 06:52

    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.

    0 讨论(0)
提交回复
热议问题