Is shiftkey pressed in JavaScript?

I wrote a JS function that allows you to enter only numbers. A copy of this feature is below:

function NumbersOnly(e) {
    var evt = e || window.event;
    if (evt) {
        var keyCode = evt.charCode || evt.keyCode;
        //Allow tab, backspace and numbers to be pressed, otherwise return false for everything.
        //(keyCode>=96 && keyCode<=105) are the numpad numbers        
        if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105) || keyCode === 9 || keyCode === 8) {


        }
        else {

            evt.returnValue = false;
        }
    }
}

This function works fine with all numbers, but my problem arises when the shift key is held down and one of the number keys is pressed. The return value is one of the characters above the numbers. For example, if I hold shift and press 7, '&' returns, but keyCode is still 55! I would expect it to be different.

So my question is how to check if the shift key is held down. I tried the following check but that did not help:

    if (keyCode === 16) {
        evt.returnValue = false;
    }
    else {

        if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105) || keyCode === 9 || keyCode === 8) {


        }
        else {

            evt.returnValue = false;
        }
    }

I am using ASP.NET 4.0.

Any help would be greatly appreciated.

Thanks in advance.

+5
source share
2 answers

, :

if(evt.shiftKey) {
 ...  //returns true if shift key is pressed
+12

event.key charCode. !

function onEvent(event) {
    const key = event.key; // "a", "1", "Shift", etc.
    if (isFinite(key)) { // Is number
        // Do work
    }
};

Mozilla

0

All Articles