Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the shiftkey held down in JavaScript

I have written a JS function that only allow numbers to be entered. A copy of that function 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 the numbers but my problem happens when the shift key is held down and one of the number keys is pressed. The value returned is one of the characters above the numbers. So for example if I hold down shift and press 7, '&' is returned but the keyCode is still 55!! I would have expected that to be different.

So my question is how do I check if the shift key is being held down. I've tried the following check but this didn't work:

    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'm using ASP.NET 4.0.

Any help would be gratefully received.

Thanks in advance.

like image 762
Sun Avatar asked May 15 '12 10:05

Sun


People also ask

What is key down in JavaScript?

The keydown event is fired when a key is pressed. Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

How can I tell if a Shift key is pressed in typescript?

In the above code, shiftKey property is used to check if the user pressed 'SHIFT' or not. The shiftKey property returns a boolean value indicating whether or not the “SHIFT” key was pressed when a key event was triggered. Similarly, you can use altKey , ctrlKey , metaKey properties to detect ALT, CTRL, META keys.

What is Shift key down?

Holding down the Shift key while pressing an arrow key highlights text one character at a time in the direction of pressing the arrow key. If you also hold down Ctrl , it highlights one word at a time. Hold down Shift. In some versions of Windows, when a disc is inserted into the computer, software automatically runs.


1 Answers

You can check if shift key is pressed using :

if(evt.shiftKey) {
 ...  //returns true if shift key is pressed
like image 64
Sudhir Bastakoti Avatar answered Sep 17 '22 12:09

Sudhir Bastakoti