我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
我对上面的答案有问题。它不包括数字键盘,如果一个按shift+数字的特殊符号也不应该显示。但是这个解没有考虑到它。
我在这篇文章中找到的最好的链接是: http://www.west-wind.com/weblog/posts/2011/Apr/22/Restricting-Input-in-HTML-Textboxes-to-Numeric-Values
我是stackoverflow的新手,所以我不知道我是否可以把更好的解决方案编辑到顶层。
其他回答
你可以尝试HTML5数字输入:
<input type="number" placeholder="enter the number" min="0" max="9">
这个输入标记元素现在只接受0到9之间的值 min属性设置为0,Max属性设置为9。
欲了解更多信息,请访问http://www.w3schools.com/html/html_form_input_types.asp
这是我不久前创建的一个快速解决方案。你可以在我的文章中了解更多:
http://ajax911.com/numbers-numeric-field-jquery/
$("#textfield").bind("keyup paste", function(){
setTimeout(jQuery.proxy(function() {
this.val(this.val().replace(/[^0-9]/g, ''));
}, $(this)), 0);
});
使用下面简单的jQuery,在文本框中只允许数字字符。您不需要手动筛选所有特殊字符,因此不会有遗漏某些特殊字符的危险。这将只允许数字0-9:(将下面的代码放在document ready中,并根据您的数字文本字段类名更改类名。)
//Event of data being keyed in to textbox with class="numericField".
$(".numericField").keyup(function() {
// Get the non Numeric char that was enetered
var nonNumericChars = $(this).val().replace(/[0-9]/g, '');
// Now set the value in text box
$(this).val( $(this).val().replace(nonNumericChars, ''));
});
你可以使用一个简单的JavaScript正则表达式来测试纯数字字符:
/^[0-9]+$/.test(input);
如果输入是数字,则返回true,否则返回false。
或事件键码,简单使用如下:
// Allow: backspace, delete, tab, escape, enter, ctrl+A and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
var charValue = String.fromCharCode(e.keyCode)
, valid = /^[0-9]+$/.test(charValue);
if (!valid) {
e.preventDefault();
}
对于你正在寻找的东西来说,它可能是多余的,但我建议使用jQuery插件autonnumeric() -它很棒!
您可以只限制数字,十进制精度,最大/最小值等。
http://www.decorplanit.com/plugin/