Javascript 使用jQuery将输入字段设置为仅接受数字
我必须定义一个只接受整数的输入文本 我尝试使用正则表达式,但值的小数部分仍然可见 我使用了这个函数:Javascript 使用jQuery将输入字段设置为仅接受数字,javascript,jquery,Javascript,Jquery,我必须定义一个只接受整数的输入文本 我尝试使用正则表达式,但值的小数部分仍然可见 我使用了这个函数: $(document).on("input","input", function(e) { this.value = this.value.replace(/[^\d\\-]/g,''); }) 简单易用。试试看: 已编辑:还调用onblur事件以防止粘贴。 功能编号(选择器){ selector.value=selector.value.replace(/[^0-9]/g'); }
$(document).on("input","input", function(e) {
this.value = this.value.replace(/[^\d\\-]/g,'');
})
简单易用。试试看: 已编辑:还调用
onblur
事件以防止粘贴。
功能编号(选择器){
selector.value=selector.value.replace(/[^0-9]/g');
}
您可以在键下检测是否为数字,您可以在粘贴事件中检查是否为数字并删除所有非数字。这也可以去除斑点
原始来源::
下面的代码已从原始源代码修改
请尝试:
$(“#输入”)。在(“粘贴”,函数(){
setTimeout(函数(){
如果($('#input').val()!=$('#input').val()。替换(/\D/g,“))
{
$('#input').val($('#input').val().replace(/\D/g,“”));
}
},10)
});
$(“#第一行”).on('keydown',“#input',函数(e){-1!=$.inArray(e.keyCode,[46,8,9,27,13])|/65 | 67 | 86 | 88/.test(e.keyCode)&(!0==e.ctrlKey | | |!0==e.metaKey)| 35=e.keyCode |(e.keyCode | |这是怎么回事
$('input')。在('input blur paste',function()上{
$(this.val($(this.val().replace(/\D/g'))
})
为什么不使用类型编号?但它在输入中也接受十进制(.),我在输入中不需要(.)。右键单击和粘贴的可能重复不会触发键控。谢谢@Archer,我以前没有考虑过。现在它已修复。现在检查它。
Finally I solved the above issue with my requirement to type only number is
$(document).on("input", ".skilltxt", function(e) {
this.value = this.value.replace(/[^\d]/g,'');
});
$(".skilltxt").on('paste',function(e) {
if(gBrowser=='IE') {
var clipboardData, pastedData;
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
}
else if((gBrowser=='Firefox')|| (gBrowser=='Chrome')){
var pastedData = (e.originalEvent || e).clipboardData.getData('text/plain');
window.document.execCommand('insertText', false, pastedData)
}
if(Math.floor(pastedData) == pastedData && $.isNumeric(pastedData)){
$(this).val($(this).val().replace(/[^\d]/g,''));
}
else{
return false;
}
});