2016-08-23 167 views
0

我給文本輸入添加了一個簡單的掩碼,只允許輸入數字。我這樣做是使用下面的代碼:窗口鍵盤鍵碼不起作用

jQuery(function($) { 
     $("#zip").keydown(function(event) { 
      // Allow only backspace and delete 
      if (event.keyCode == 46 || event.keyCode == 8) { 
       // let it happen, don't do anything 
      } 
      else { 
       // Ensure that it is a number and stop the keypress 
       if (event.keyCode < 48 || event.keyCode > 57) { 
        event.preventDefault(); 
       } 
      } 
     }); 
    }); 

我來跨越的問題是,小鍵盤數字不能在Windows上工作(他們的工作找到在Mac上)。但是,鍵盤上排的數字正常工作。有沒有人遇到過這個?

回答

1

您還沒有包括在你的if語句的數字小鍵碼。這應該工作:

jQuery(function($) { 
    $("#zip").keydown(function(event) { 
     // Allow only backspace and delete 
     if (event.keyCode == 46 || event.keyCode == 8) { 
      // let it happen, don't do anything 
     } 
     else { 
      // Ensure that it is a number and stop the keypress 
      if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) { 
       event.preventDefault(); 
      } 
     } 
    }); 
}); 
1

您可以使用:

jQuery(function($) { 
     $("#zip").keydown(function(event) { 
      var code = e.keycode || e.which 
      // Allow only backspace and delete 
      if (code == 46 || code == 8) { 
       // let it happen, don't do anything 
      } 
      else { 
       // Ensure that it is a number and stop the keypress 
       if (code < 48 || code > 57) { 
        event.preventDefault(); 
       } 
      } 
     }); 
    });