Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

keypress - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can check if shift key is pressed using :

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...