![](/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.