输入类型数字,只接受数字,不接受字母jQuery
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
遇到了一些问题;当我单击它时,即使它仍然empty
,也会alert
它不是一个数字,所以我添加了另一个代码:
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");
}
}
});
Demo@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">
相关文章:
- 如何为jQuery屏蔽输入插件创建一个允许字母数字、空格和重音字符的掩码
- 在Jquery倒计时计时器上设置每个数字的动画
- 如何在jquery+javascript中只在输入框中输入数字(使用regex)
- 使用jquery重写html数字
- jquery检查数字是否键入了isNaN
- 一个jquery验证器方法,它不接受纯数字或纯特殊字符,但接受上面是否有字母
- 通过jQuery函数将拉丁数字更改为波斯数字并添加逗号
- 打印到控制台时为NaN,但typeof为数字jquery
- 如何使用jquery对货币格式的数字求和
- 计算content中的数字总和使用Jquery可编辑文本
- 在jquery中,将文本框验证为数字
- 正则表达式 jquery 将数字替换为链接
- jQuery - 带有一些数字的表格计算出现奇怪的舍入错误
- javascript/jquery 数字时钟脚本,24 小时格式,带有日期
- 输入类型数字,只接受数字,不接受字母jQuery
- jQuery UI Slider ui.value 获取最后一个数字
- 查找数组中的下一个最高数字 - jquery
- 迭代和选择那些唯一的数字(jQuery)
- 老虎机风格的数字jquery
- ";[对象对象]";不是有效的数字jquery滑块