什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
您可以通过添加模式对文本输入使用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]的解决方案,请参阅我的完整答案
其他回答
这个函数做同样的事情,使用上面的一些想法。
$field.keyup(function(){
var val = $j(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2) val =val.replace(/\.+$/,"");
}
$j(this).val(val);
});
显示视觉反馈(出现错误字母后消失) 允许小数 捕获多个”。 没有问题的左/右del等。
只需通过parseFloat()运行内容。它将在无效输入时返回NaN。
我有一段代码,它很好地完成了这项工作。
var prevVal = '';
$(".numericValue").on("input", function (evt) {
var self = $(this);
if (self.val().match(/^-?\d*(\.(?=\d*)\d*)?$/) !== null) {
prevVal = self.val()
} else {
self.val(prevVal);
}
if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57) && (evt.which != 45 && self.val().indexOf("-") == 0)) {
evt.preventDefault();
}
});
下面是我用来阻止击键的。这只允许数字0-9和小数点。易于实现,不需要大量代码,并且工作起来很有魅力:
<script>
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
} else {
return true;
}
}
</script>
<input value="" onkeypress="return isNumberKey(event)">
我使用这个函数,它工作得很好
$(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;
}
});
});