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;
        }
        //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)
                {

....

选项卡功能不起作用。我在这里做错了什么?

4

2 回答 2

1

你需要修改你的条件来逃避backspacetab。使用&&代替||

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);
    }
于 2012-12-11T17:36:21.447 回答
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);
        }
    }
于 2012-12-12T14:42:36.900 回答