什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
请在脚本底部添加:
if(this.value.length == 1 && this.value == 0)
this.value = "";
其他回答
此代码属于文本框中的字母限制,在按键事件时必须输入唯一数字验证。希望对你有所帮助
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;
}
}
我使用这个函数,它工作得很好
$(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;
}
});
});
您可以通过添加模式对文本输入使用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]的解决方案,请参阅我的完整答案
我认为这是解决这个问题的好方法,而且非常简单:
$(function() {
var pastValue, pastSelectionStart, pastSelectionEnd;
$("input").on("keydown", function() {
pastValue = this.value;
pastSelectionStart = this.selectionStart;
pastSelectionEnd = this.selectionEnd;
}).on("input propertychange", function() {
var regex = /^[0-9]+\.?[0-9]*$/;
if (this.value.length > 0 && !regex.test(this.value)) {
this.value = pastValue;
this.selectionStart = pastSelectionStart;
this.selectionEnd = pastSelectionEnd;
}
});
});
例如:JSFiddle
场景覆盖
这里的大多数类似建议至少不能满足其中一项要求,或者需要大量代码来覆盖所有这些场景。
只允许1个小数点。 允许home键、结束键和方向键。 允许在任何索引上使用删除和退格。 允许在任何索引处编辑(只要输入匹配正则表达式)。 允许使用ctrl+v和shift+insert进行有效输入(与右键单击+粘贴相同)。 不闪烁文本值,因为没有使用keyup事件。 恢复无效输入后的选择。
失败场景
从0.5开始,只删除0是不行的。这可以通过将正则表达式更改为/^[0-9]*\.?[0-9]*$/,然后添加一个模糊事件,当文本框以小数点开始时(如果需要)在0前面。请参阅此高级场景,以更好地了解如何修复此问题。
插件
我创建了这个简单的jquery插件,使这更容易:
$("input").limitRegex(/^[0-9]+\.?[0-9]*$/);
我认为最好的答案就是上面的方法。
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, '');
}
});
这样,如果有任何按钮点击,不会导致文本被改变,忽略它。有了这个,你可以点击箭头和删除,而不跳到最后,但它清除任何非数字文本。