开发者

Handle key using javascript onkeydown

开发者 https://www.devze.com 2023-04-07 08:40 出处:网络
I have this code function verifyKey(e) { var keycode; if (window.event) keycode = window.event.keyCode; else if (e)

I have this code

function verifyKey(e)
{
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;
    regex=/[1-9]/;
    if(regex.test(keycode))
        return true;
    else
        void(0);
}

in the html I added an input and I add the onkeydown event onkeydown="verifyKey(event);"

I like to verify the key before it display on the text

If the key is a number or coma(,) or full stop(.) then accept the key else refuse i开发者_如何学编程t

Thanks


Here in your code you are testing the regular expression defined with the keycode, so every chearactes on the keyboard will be allowed since the keycode of every key is numbers, so you will not get the result what you expect. Instead of using the regular expression try the below code

<html>
<head>
<script type="text/javascript">
function verifyKey(e)
{
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;


    if((keycode>=48 && keycode<=57))
    {alert("if")
        return true;
    }
    else if((keycode == 188)||(keycode == 190))
    {alert("elseif");
        return true;
    }
    else
    {alert("else")
        return false;
    }
}


</script>
</head>
<body>
<input type="text" onkeypress="return verifyKey(event)" />
</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号