什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
你可以使用来自decorplanit.com的autoNumeric。它们对数字、货币、舍入等都有很好的支持。
我曾经在IE6环境下使用过,只做了一些css调整,结果还算成功。
例如,可以定义一个css类numericInput,它可以用来用数字输入掩码装饰字段。
改编自autoNumeric网站:
$('input.numericInput').autoNumeric({aSep: '.', aDec: ','}); // very flexible!
其他回答
你看不到字母的神奇出现和消失的关键下来。这也适用于鼠标粘贴。
$('#txtInt').bind('input propertychange', function () {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
此代码属于文本框中的字母限制,在按键事件时必须输入唯一数字验证。希望对你有所帮助
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;
}
}
上面提到的numeric()插件在Opera中不起作用(你不能退格,不能删除,甚至不能使用后退或前进键)。
下面的代码在JQuery或Javascript都可以完美地工作(它只有两行)。
JQuery:
$(document).ready(function() {
$('.key-numeric').keypress(function(e) {
var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
if (verified) {e.preventDefault();}
});
});
Javascript:
function isNumeric(e)
{
var keynum = (!window.event) ? e.which : e.keyCode;
return !((keynum == 8 || keynum == undefined || e.which == 0) ? null : String.fromCharCode(keynum).match(/[^0-9]/));
}
当然,这只适用于纯数字输入(加上退格键、删除键、前进/后退键),但可以很容易地更改为包含点和减号字符。
我使用这个函数,它工作得很好
$(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;
}
});
});
我认为最好的答案就是上面的方法。
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
但我同意这是一个有点痛苦的方向键和删除按钮快照光标到字符串的末尾(因为它被踢回给我在测试)
我添加了一个简单的更改
$('.numbersOnly').keyup(function () {
if (this.value != this.value.replace(/[^0-9\.]/g, '')) {
this.value = this.value.replace(/[^0-9\.]/g, '');
}
});
这样,如果有任何按钮点击,不会导致文本被改变,忽略它。有了这个,你可以点击箭头和删除,而不跳到最后,但它清除任何非数字文本。