我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
检查小数点是否已经使用:-
// Stop: Multiple decimal points
if((e.keyCode == 190 || e.keyCode == 110) && ((this.value).indexOf(".") >= 0))
e.preventDefault();
其他回答
$(document).on("keypress", ".classname", function(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
});
你可以尝试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
这似乎牢不可破。
// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
this.value = this.value.replace(/[^0-9\.]+/g, '');
if (this.value < 1) this.value = 0;
});
// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});
您可以使用以下代码。
<input type=“text” onkeypress=“return event.charCode >= 48 && event.charCode <= 57”>
$(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
}