什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
上面提到的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]/));
}
当然,这只适用于纯数字输入(加上退格键、删除键、前进/后退键),但可以很容易地更改为包含点和减号字符。
其他回答
检查数据库使用的查找代码:
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)'
你可以使用带有number()方法的Validation插件。
$("#myform").validate({
rules: {
field: {
required: true,
number: true
}
}
});
保持插入符号在输入中的位置的其他方法:
$(document).ready(function() {
$('.numbersOnly').on('input', function() {
var position = this.selectionStart - 1;
fixed = this.value.replace(/[^0-9\.]/g, ''); //remove all but number and .
if(fixed.charAt(0) === '.') //can't start with .
fixed = fixed.slice(1);
var pos = fixed.indexOf(".") + 1;
if(pos >= 0)
fixed = fixed.substr(0,pos) + fixed.slice(pos).replace('.', ''); //avoid more than one .
if (this.value !== fixed) {
this.value = fixed;
this.selectionStart = position;
this.selectionEnd = position;
}
});
});
优点:
用户可以使用方向键、退格键、删除键、… 当你想要粘贴数字的时候就可以了
Plunker:演示工作
此代码属于文本框中的字母限制,在按键事件时必须输入唯一数字验证。希望对你有所帮助
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;
}
}
使用按键事件
数组的方法
var asciiCodeOfNumbers = [48, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57]
$(".numbersOnly").keypress(function (e) {
if ($.inArray(e.which, asciiCodeOfNumbers) == -1)
e.preventDefault();
});
直接法
$(".numbersOnly").keypress(function (e) {
if (e.which < 48 || 57 < e.which)
e.preventDefault();
});