使用键事件时Tab键事件不起作用

时间:2012-12-11 17:31:57

标签: javascript jquery keyboard

我正在使用以下功能检查按键号码

function only_numeric(e)
    {
        var keynum;
        var keychar;
        var numcheck;
        if(window.event) // IE
        {
            keynum = e.keyCode;
        }
        else if(e.which) // netscape/Firefox/opera
        {
            keynum = e.which;
        }
        //condition for backspace(music) Key
        if(keynum != 8)
        {
            keychar = String.fromCharCode(keynum);
            //numcheck = /\d/;
            numcheck = /[.0-9]/;
            return numcheck.test(keychar);
        }
        else
        {
            return true;
        }
    }

我在输入框中调用了上面的函数,

<input required="" onkeypress='return only_numeric(event,this.id)' type="text" name="test1" id="test1"  />


<input required="" onkeypress='return only_numeric(event,this.id)' type="text" name="test2" id="test2"  />

验证号码功能正常。我需要使用tabkey代码(9),就像退格键代码8一样。如果我在only_numeric函数中使用如下代码

...

    if(keynum != 8 || keynum != 9)
                {

....

标签功能不起作用。我在这里做错了什么?。

2 个答案:

答案 0 :(得分:1)

您需要修改条件以转义退格标签。使用&&代替||

if(keynum != 8 && keynum != 9)

另外,我会简单地重新安排你的情况,如下,

    if(keynum == 8 || keynum == 9) /* and more keys to escape*/
    {
         return true;
    }
    else
    {
        keychar = String.fromCharCode(keynum);
        //numcheck = /\d/;
        numcheck = /[.0-9]/;
        return numcheck.test(keychar);
    }

答案 1 :(得分:0)

是肯定的。我终于得到了输出,我修改了我的功能如下,

function only_numeric(e)
    {
        var keynum;
        var keychar;
        var numcheck;
        if(window.event) // IE
        {
            keynum = e.keyCode;
        }
        else if(e.which) // netscape/Firefox/opera
        {
            keynum = e.which;
        }

         var tabkey = e.keyCode;

         if( keynum == 8 || tabkey == 9 || tabkey == 37 || tabkey == 39)
        {
                  return true;
        }        

        else
        {
             keychar = String.fromCharCode(keynum);
            //numcheck = /\d/;
            numcheck = /[.0-9]/;
            return numcheck.test(keychar);
        }
    }