什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
Praveen Jeganathan报道
不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。 参见:https://stackoverflow.com/a/20186188/66767
什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
Praveen Jeganathan报道
不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。 参见:https://stackoverflow.com/a/20186188/66767
当前回答
这是我刚刚完成的一个代码片段(使用Peter Mortensen / Keith Bentrup的一部分代码),用于对文本字段进行整数百分比验证(jQuery是必需的):
/* This validates that the value of the text box corresponds
* to a percentage expressed as an integer between 1 and 100,
* otherwise adjust the text box value for this condition is met. */
$("[id*='percent_textfield']").keyup(function(e){
if (!isNaN(parseInt(this.value,10))) {
this.value = parseInt(this.value);
} else {
this.value = 0;
}
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value,10) > 100) {
this.value = 100;
return;
}
});
这段代码:
允许使用主数字键和数字键盘。 验证以排除shift数字字符(例如#,$,%等) 将NaN值替换为0 替换为100个大于100的值
我希望这能帮助到那些需要帮助的人。
其他回答
你可以使用带有number()方法的Validation插件。
$("#myform").validate({
rules: {
field: {
required: true,
number: true
}
}
});
我使用这个函数,它工作得很好
$(document).ready(function () {
$("#txt_Price").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
//if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57))
if ((e.which != 46 || $(this).val().indexOf('.') != -1) && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
在这里找到了一个很好的解决方案http://ajax911.com/numbers-numeric-field-jquery/
我只是按照我的要求把“键上”改为“键下”
此代码属于文本框中的字母限制,在按键事件时必须输入唯一数字验证。希望对你有所帮助
HTML标记:
<input id="txtPurchaseAmnt" style="width:103px" type="text" class="txt" maxlength="5" onkeypress="return isNumberKey(event);" />
函数onlyNumbers(key) {
var keycode = (key.which) ? key.which : key.keyCode
if ((keycode > 47 && keycode < 58) || (keycode == 46 || keycode == 8) || (keycode == 9 || keycode == 13) || (keycode == 37 || keycode == 39)) {
return true;
}
else {
return false;
}
}
您可以通过添加模式对文本输入使用HTML5验证。不需要使用regex或keyCodes手动验证。
<input type="text" pattern="[0-9.]+" />
$("input[type=text][pattern]").on("input", function () {
if (!this.checkValidity())
this.value = this.value.slice(0, -1);
});
对于输入[type=number]的解决方案,请参阅我的完整答案