我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
$(document).ready(function()
{
$("#textBoxId").bind("change",checkInput);
});
function checkInput()
{
// check if $('#textBoxId').val() is under your constraints
// then change its value, removing the last character
// since this event will be called each time you
// type a character
}
其他回答
function Numbers(e)
{
if($.browser.msie)
{
if(e.keyCode > 47 && e.keyCode < 58)
return true;
else
return false;
}
else
{
if((e.charCode > 47 && e.charCode < 58) || (e.charCode == 0))
return true;
else
return false;
}
}
我希望这在所有浏览器上都能工作。
在document.ready中添加以下代码
$('.class of text box').keyup(function ()
{
this.value = this.value.replace(/[^0-9]/g, '');
});
这里有两种不同的方法:
允许有小数点的数值 允许没有小数点的数值
方法1:
$ (" # approach1”)。上(“keypress keyup blur”,function (e) (这个美元)。瓦尔(这)。瓦尔(美元)。replace(0 - 9 \。- [^]/ g,”); 如果(e .哪! = 46 | |美元(这)。瓦尔indexOf()。 ('.') != - 1) &&(事件)。哪种< 48 | |事件。哪个> 57) 事件。preventDefault (); 的 }); <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < / > <h2>Numeric与decimal point</h2><br/> <跨越>输入数量< /跨越> <输入类型=“文本”
方法2:
$ (" # approach2”)。上(“keypress keyup blur”,功能(事件) (这个美元)。瓦尔(这)。瓦尔(美元)。replace (- [^ \ d]。+ -”、“); 如果(事件。哪种< 48 | |事件。哪个> 57) 事件。preventDefault (); 的 }); <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < / > <h2>Numeric without decimal point</h2><br/> <跨越>输入数量< /跨越> <输入类型=“文本”
使用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)');
如果你必须解决变音符和特殊字符,尝试使用这个:
$(this).on( 'keypress', function( e )
{
// Ensure that it is a number and stop the keypress
if (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) {
e.preventDefault();
}
});