什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
我使用这个函数,它工作得很好
$(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;
}
});
});
其他回答
检查数据库使用的查找代码:
function numonly(root){
>>var reet = root.value;
var arr1 = reet.length;
var ruut = reet.charAt(arr1-1);
>>>if (reet.length > 0){
var regex = /[0-9]|\./;
if (!ruut.match(regex)){
var reet = reet.slice(0, -1);
$(root).val(reet);
>>>>}
}
}
//Then use the even handler onkeyup='numonly(this)'
下面是我用来阻止击键的。这只允许数字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)">
在这里找到了一个很好的解决方案http://ajax911.com/numbers-numeric-field-jquery/
我只是按照我的要求把“键上”改为“键下”
根据CanIUse的数据,截至2015年10月,HTML5支持输入类型数字,全球浏览器的支持度高达88%以上。
<input type="number" step="0.01" min="0" name="askedPrice" id="askedPrice" />
这不是JQuery相关的解决方案,但优点是在手机上的Android键盘会对输入数字进行优化。
或者,也可以使用带有新参数"pattern"的输入类型文本。更多细节在HTML5规范。
我认为它比jquery解决方案更好,因为在这个问题中提供的jquery解决方案不支持千位分隔符。如果你能使用html5。
JSFiddle: https://jsfiddle.net/p1ue8qxj/
我用了这个,效果很好。
ini=$("#id").val();
a=0;
$("#id").keyup(function(e){
var charcode = (e.which) ? e.which : e.keyCode;
// for decimal point
if(!(charcode===190 || charcode===110))
{ // for numeric keys andcontrol keys
if (!((charcode>=33 && charcode<=57) ||
// for numpad numeric keys
(charcode>=96 && charcode<=105)
// for backspace
|| charcode==8))
{
alert("Sorry! Only numeric values allowed.");
$("#id").val(ini);
}
// to include decimal point if first one has been deleted.
if(charcode===8)
{
ini=ini.split("").reverse();
if(ini[0]==".")
a=0;
}
}
else
{
if(a==1)
{
alert("Sorry! Second decimal point not allowed.");
$("#id").val(ini);
}
a=1;
}
ini=$("#id").val();
});
find keycodes at http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes