我在JavaScript表單域中使用onkeyup事件,並且我想檢查按下的鍵是否是數字 - 即。 0 - 9,所以我可以對輸入做些什麼。Javascript:如何檢查表單域上按下的鍵是否是數字(0 - 9)?
<input type="text" onkeyup="" />
我需要使用正則表達式嗎?
感謝
我在JavaScript表單域中使用onkeyup事件,並且我想檢查按下的鍵是否是數字 - 即。 0 - 9,所以我可以對輸入做些什麼。Javascript:如何檢查表單域上按下的鍵是否是數字(0 - 9)?
<input type="text" onkeyup="" />
我需要使用正則表達式嗎?
感謝
看到這個:
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>
這不是確切的,你還必須插入他們的數字鍵盤號碼。 http://www.cambiaresearch.com/articles/15/javascript-key-codes – Asterius 2016-03-18 15:02:47
這是不正確的。它不處理數字鍵盤鍵 – 2017-03-21 02:10:35
我用下面的函數來檢查,如果給定的字符串是數字或不
// 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)));
使用event.key
獲取實際值。要檢查是否整數,只要使用isFinite
input.addEventListener("keydown", function(event) {
const isNumber = isFinite(event.key);
});
更簡單的HTML的解決辦法是使用number
類型的輸入。它僅限於數字(種類)。
<input type="number">
無論哪種方式,你應該清理所有的用戶輸入:
string.replace(/[^0-9]/g,'');
只允許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;
});
+1用戶重定向到前面計算器條目。 – ChristopheD 2009-09-09 21:15:29
除了第三個是這篇文章.... – wows 2009-09-09 21:19:54
@wows - 呵呵,對不起,刪除它。 – karim79 2009-09-09 21:26:38