![](/img/trans.png)
[英]HTML Field Type Input Number Only or Letter Only Without JavaScript
[英]input type number, accepts number only not letter jquery
$("#number").bind('keyup change click', function() {
if ($(this).val().match(/^\d+$/)) {
} else {
alert("Not a number");
}
這是我的代碼,用於獲取僅來自用戶的數字輸入。 沒關系,但start of click
遇到了一些問題; 當我點擊它時會alert
它不是一個數字,即使它仍然是empty
所以我添加了另一個代碼:
if ($(this).val().length === 0) {
}
從代碼的開頭。 它確實解決了空的問題或開始點擊問題是當我輸入letters
它does not alert
消息。 如何解決這個問題?任何建議都表示贊賞
@Rias有上面的答案,但是,您也可以執行以下操作。
$("#number").bind('keyup change click', function() {
//Check only if the text box is not empty
if ( $.trim($(this).val()) != "") {
if ($(this).val().match(/^\d+$/)) {
} else {
alert("Not a number");
}
}
});
演示@Fiddle
更新:如果您要刪除任何非數字字符,請嘗試以下操作。
$("#number").bind('keyup change click', function() {
if ( $.trim($(this).val()) != "") {
if ($(this).val().match(/^\d+$/)) {
} else {
alert("Not a number");
$(this).val( $(this).val().replace(/[^0-9]+/gi, "") );
}
}
});
將正則表達式更改為/^\\d*$/
並且它也將接受空字段,因為量詞*
接受0個或更多字符類型\\d
數字,而+
需要1個或更多個數字來匹配。
$(document).ready(function() { $("#number").bind('keyup change click', function() { if ($(this).val().match(/^\\d*$/)) { } else { alert("Not a number"); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="number">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.