2009-09-09 37 views

回答

-1

看到這個:

http://www.javascriptkit.com/javatutors/javascriptkey2.shtml

<script type="text/javascript"> 
function displayunicode(e){ 
var unicode=e.keyCode? e.keyCode : e.charCode 
if unicode >= 48 && unicode <= 57 { 
    alert('number') 
} 
else{ 
} 
    alert('nonnumber') 
} 
</script> 
<form> 
<input type="text" size="2" maxlength="1" onkeyup="displayunicode(event); this.select()" /> 
</form> 
+0

這不是確切的,你還必須插入他們的數字鍵盤號碼。 http://www.cambiaresearch.com/articles/15/javascript-key-codes – Asterius 2016-03-18 15:02:47

+0

這是不正確的。它不處理數字鍵盤鍵 – 2017-03-21 02:10:35

1

我用下面的函數來檢查,如果給定的字符串是數字或不

// Validate Numeric inputs 
function isNumber(o) { 
    return o == '' || !isNaN(o - 0); 
} 

假設上的keyup或keydown事件的關鍵代碼在鍵代碼變量:

var keyCode = e.keyCode || e.which; 
if (keyCode >= 96 && keyCode <= 105) { 
     // Numpad keys 
     keyCode -= 48; 
} 
console.log(isNumber(String.fromCharCode(keyCode))); 
0

使用event.key獲取實際值。要檢查是否整數,只要使用isFinite

input.addEventListener("keydown", function(event) { 
    const isNumber = isFinite(event.key); 
}); 

更簡單的HTML的解決辦法是使用number類型的輸入。它僅限於數字(種類)。

<input type="number"> 

無論哪種方式,你應該清理所有的用戶輸入:

string.replace(/[^0-9]/g,''); 
0

只允許0-9,其他字母將被吞噬。

$('#id').keypress(function (e) { 
      var validkeys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; 
      if (validkeys.indexOf(e.key) < 0) 
       return false; 
     }); 
相關問題