什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
/* 这是我的跨浏览器版本 如何允许只有数字(0-9)在HTML输入框使用jQuery? * /
$("#inputPrice").keydown(function(e){
var keyPressed;
if (!e) var e = window.event;
if (e.keyCode) keyPressed = e.keyCode;
else if (e.which) keyPressed = e.which;
var hasDecimalPoint = (($(this).val().split('.').length-1)>0);
if ( keyPressed == 46 || keyPressed == 8 ||((keyPressed == 190||keyPressed == 110)&&(!hasDecimalPoint && !e.shiftKey)) || keyPressed == 9 || keyPressed == 27 || keyPressed == 13 ||
// Allow: Ctrl+A
(keyPressed == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(keyPressed >= 35 && keyPressed <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (e.shiftKey || (keyPressed < 48 || keyPressed > 57) && (keyPressed < 96 || keyPressed > 105 )) {
e.preventDefault();
}
}
});
其他回答
我用了这个,效果很好。
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
你可以使用来自decorplanit.com的autoNumeric。它们对数字、货币、舍入等都有很好的支持。
我曾经在IE6环境下使用过,只做了一些css调整,结果还算成功。
例如,可以定义一个css类numericInput,它可以用来用数字输入掩码装饰字段。
改编自autoNumeric网站:
$('input.numericInput').autoNumeric({aSep: '.', aDec: ','}); // very flexible!
只需通过parseFloat()运行内容。它将在无效输入时返回NaN。
您可以通过添加模式对文本输入使用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]的解决方案,请参阅我的完整答案
根据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/