Nice programing

숫자 키패드의 keyCode 값?

nicepro 2020. 11. 16. 22:10
반응형

숫자 키패드의 keyCode 값?


숫자 키패드의 숫자가 키보드 상단의 숫자와 다른 키 코드를 가지고 있습니까?

다음은 keyup 이벤트에서 실행되어야하는 JavaScript입니다. 그러나 키 코드가 48에서 57 사이 인 경우에만 해당됩니다. 코드는 다음과 같습니다.

$('#rollNum').keyup(function(e) {
    if(e.keyCode >= 48 && e.keyCode <= 57) { //0-9 only
        var max = 15;
        var textLen = $(this).val().length;
        var textLeft = max - textLen;
        . . . 

내 문제는이 코드가 키보드 상단에 입력 된 숫자에 대한 응답으로 만 실행되고 숫자 키패드에서 입력 된 숫자에 응답으로 실행되지 않는다는 것입니다.

대답은 숫자 키패드가 다른 keyCode 값을 가지고 있다는 것이어야한다고 생각하는데, 그것들이 무엇인지 어떻게 알 수 있습니까?


키 코드가 다릅니다. 키패드 0-9 키 코드입니다 96105

귀하의 if성명해야한다 :

if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) { 
    // 0-9 only
}

다음 은 키 코드에 대한 참조 가이드입니다.


******************* KEYCODE를 사용하지 마세요 !!!! ******************

keyCode 의 문제 는 키보드 상단의 숫자와 결합 된 키 를 피하는 것입니다. e @ & "{} ... 와 같은 특수 문자를 피하기 위해 "Shift ""Alt " 키에 체크를 추가해야합니다 .

가장 간단한 해결책은 e.key 를 숫자 로 변환 하고 변환이 NaN을 제공하는지 확인하는 것입니다 !

let key = Number(e.key)
if (isNaN(key) || e.key===null) {
  console.log("is not numeric")
}
else {
  console.log("is numeric")
}

주의 e.key 인 경우 는 null , 그것은 제공 0 !

Number(5)         // => 5
Number('5')       // => 5
Number(null)      // => 0
Number('chars')   // => NaN
Number(undefined) // => NaN

간단히 실행할 수 있습니다.

$(document).keyup(function(e) {
    console.log(e.keyCode);
});

브라우저 콘솔에서 누른 키의 코드를 확인합니다.

또는 여기에서 키 코드를 찾을 수 있습니다 : https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#Numpad_keys


keyCode는 숫자 키패드의 숫자와 키보드 상단의 숫자에 따라 다릅니다.

keyCodes :

키보드 상단의 숫자 (0-9) : 48-57
숫자 키패드의 숫자 (0-9) : 96-105

자바 스크립트 조건 :

if((e.keyCode >= 48 && e.keyCode <=57) || (e.keyCode >= 96 && e.keyCode <=105)) { 
    // entered key is a number
}

모든 키 코드에 대한 참조 (데모 포함) : http://www.codeforeach.com/javascript/keycode-for-each-key-and-usage-with-demo


CTRL + C, CTRL-V 솔루션을 원하는 사람들을 위해 여기에 있습니다.

    /**
     * Retrieves the number that was pressed on the keyboard.
     *
     * @param {Event} event The keypress event containing the keyCode.
     * @returns {number|null} a number between 0-9 that was pressed. Returns null if there was no numeric key pressed.
     */
    function getNumberFromKeyEvent(event) {
        if (event.keyCode >= 96 && event.keyCode <= 105) {
            return event.keyCode - 96;
        } else if (event.keyCode >= 48 && event.keyCode <= 57) {
            return event.keyCode - 48;
        }
        return null;
    }

첫 번째 답변의 논리를 사용합니다.


@ .A.의 대답. Morel 나는 작은 풋 프린트로 이해하기 가장 쉬운 솔루션이라고 생각합니다. 더 적은 양의 코드를 원하면 Morel을 수정 한이 솔루션은 악명 높은 'e'문자를 포함하여 어떤 종류의 문자도 허용하지 않는 데 적합합니다.

function InputTypeNumberDissallowAllCharactersExceptNumeric() {
  let key = Number(inputEvent.key);
  return !isNaN(key);
}

다른 답변에 추가하려면 다음 사항에 유의하세요.

  • keyup and keydown differ from keypress
  • if you want to use String.fromCharCode() to get the actual digit from keyup, you'll need to first normalize the keyCode.

Below is a self-documenting example that determines if the key is numeric, along with which number it is (example uses the range function from lodash).

const isKeypad = range(96, 106).includes(keyCode);
const normalizedKeyCode = isKeypad ? keyCode - 48 : keyCode;
const isDigit = range(48, 58).includes(normalizedKeyCode);
const digit = String.fromCharCode(normalizedKeyCode);

You can use this to figure out keyCodes easily:

$(document).keyup(function(e) {
    // Displays the keycode of the last pressed key in the body
    $(document.body).html(e.keyCode);
});

http://jsfiddle.net/vecvc4fr/

참고URL : https://stackoverflow.com/questions/13196945/keycode-values-for-numeric-keypad

반응형