最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Handle key using javascript onkeydown - Stack Overflow

programmeradmin1浏览0评论

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 a(,) or full stop(.) then accept the key else refuse it

Thanks

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 a(,) or full stop(.) then accept the key else refuse it

Thanks

Share Improve this question edited Sep 26, 2011 at 12:38 Pointy 414k62 gold badges595 silver badges629 bronze badges asked Sep 26, 2011 at 12:35 RadRad 4,9414 gold badges27 silver badges28 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 7

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)

  1. 暂无评论