我有一个名为restrict-numbers 的类的输入文件,我想将输入的字符限制为只接受数字,我使用了下面的代码,这很好,但是我想要进行相同的限制的问题适用于在输入中粘贴在没有完全禁用粘贴的情况下提交:
function input_only_numbers(){
$("input[type=text]").each(function(){
if( $(this).hasClass("restrict-numbers") ){
$(this).keydown(function(event) {
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: Ctrl+V
(event.ctrlKey == true && (event.which == '118' || event.which == '86')) ||
// Allow: Ctrl+c
(event.ctrlKey == true && (event.which == '99' || event.which == '67')) ||
// Allow: Ctrl+x
(event.ctrlKey == true && (event.which == '120' || event.which == '88')) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if ( event.shiftKey|| (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 ) ){
event.preventDefault();
}
}
});
}
});
}