2010-04-13 76 views
1

我想弄清楚为什么我的JavaScript代码不限制数字输入。这里的代码如下:限制数字输入JavaScript问题

(function(){ 
       if(window.addEventListener) window.addEventListener("load",init,false); 
       else if(window.attachEvent) window.attachEvent("onload",init); 

       function init() { 
        var keytest = document.getElementById("keytest"); 

        function numericinput(event) { 
         var e = event || window.event; 
         var key = e.charcode || e.keyCode; 
         var regex =/^\d+\.?\d{4}$/; 
         key = String.fromCharCode(key);  

         if (!regex.test(key)) { 
           alert("something"); 

          //if(e.preventDefault) e.preventDefault(); 
          //if(e.returnValue) e.returnValue = false; 
          //return false; 
         } 
         else { //return true; 
          alert("something else"); 
         }          
        } 

        if(keytest.addEventListener) keytest.addEventListener("keypress",numericinput,false); 
        else { 
         keytest.onkeypress = numericinput(); 
        } 
       } 
      })(); 

回答

0

您使用e.charcode但它应该是e.charCode

你的正则表达式是有点过了过了,你将需要处理回空间等

您可能以及检查键码本身see