input只能输入数字


方法一:

<input type="text" name="url" onkeypress="event.returnValue=IsNum()">

<script>

function IsNum()
    {
           return ((event.keyCode >= 48) && (event.keyCode <= 57));
    }

</script>

在IE里没问题,firefox不支持event.keyCode,event.returnValue。

方法二:

<input type="text" name="url" onkeypress="return IsNum(event)">

<script>

function IsNum(e)
    {
           var key = window.event ? e.keyCode:e.which;
         var keychar = String.fromCharCode(key);
          reg = /\d/;
         return reg.test(keychar);
    }

</script>

firefox,IE都支持,可是把删除键也屏蔽了。

最后解决办法:

<input type="text" name="url" onkeypress="IsNum(event)">

<script>

function IsNum(e)
{
      var k = window.event ? e.keyCode:e.which;
     if (((k >= 48) && (k <= 57)) || k==8 || k==0)
     {
     }else
   {
         if(window.event)
          {
               window.event.returnValue = false;
        }
        else
         {
               e.preventDefault();//for firefox
       }
   }

}
</script>