我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
为什么这么复杂?你甚至不需要jQuery,因为有一个HTML5的模式属性:
<input type="text" pattern="[0-9]*">
最酷的是它在移动设备上显示了一个数字键盘,这比使用jQuery好多了。
其他回答
这就是我最近写这篇文章的原因。我知道这个问题已经有人回答了,但我把它留到以后使用。
该方法只允许0-9键盘和numpad,退格,制表符,左右箭头(正常形式操作)
$(".numbersonly-format").keydown(function (event) {
// Prevent shift key since its not needed
if (event.shiftKey == true) {
event.preventDefault();
}
// Allow Only: keyboard 0-9, numpad 0-9, backspace, tab, left arrow, right arrow, delete
if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46) {
// Allow normal operation
} else {
// Prevent the rest
event.preventDefault();
}
});
你可以尝试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
这将在添加非数字字符时保持先前的值。
$(document).on('input', '.digit-input', function() {
var prevVal = $(this).attr('ov') ? $(this).attr('ov') : '';
var newVal = this.value.replace(/[^0-9]/g, '');
this.value = newVal != '' ? newVal : prevVal;
$(this).attr('ov', this.value);
});
$(文件)。据(’input’'。digit-input',函数(){ var prevVal = $(this).attr('ov') ?$(this).attr('ov'): "; var newVal = this.value。回想起(^ [0 - 9]/ g '); this。= = " ? "newVal: prevVal; $ (this)。attr(’ov’this.value); }); < script " src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > / < script > <input type="text" class=" digital -input">
下面是另一种方法。这也可以用于粘贴。[用于字母-数字验证]
//Input Validation
var existingLogDescription = "";
$('.logDescription').keydown(function (event) {
existingLogDescription = this.value;
});
$('.logDescription').keyup(function () {
if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
alert("Log Description should contain alpha-numeric values only");
this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
this.value = existingLogDescription;
}
});
使用jQuery.validate做一些相当简单的事情
$(document).ready(function() {
$("#formID").validate({
rules: {
field_name: {
numericOnly:true
}
}
});
});
$.validator.addMethod('numericOnly', function (value) {
return /^[0-9]+$/.test(value);
}, 'Please only enter numeric values (0-9)');