设置input只能输入数字

(1)限制input只能输入整型的整数或浮点型的小数:
function prevent(e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
function digitInput(el, e) {
var ee = e || window.event; // FF、Chrome IE下获取事件对象
var c = e.charCode || e.keyCode; //FF、Chrome IE下获取键盘码
//var txt = $ (‘label’).text();
//$ (‘label’).text(txt + ’ ’ + c);
var val = el.val();
if (c == 110 || c == 190){ // 110 (190) - 小(主)键盘上的点
(val.indexOf(".") >= 0 || !val.length) && prevent(e); // 已有小数点或者文本框为空,不允许输入点
} else {
if ((c != 8 && c != 46 && // 8 - Backspace, 46 - Delete
(c < 37 || c > 40) && // 37 (38) (39) (40) - Left (Up) (Right) (Down) Arrow
(c < 48 || c > 57) && // 48~57 - 主键盘上的0~9
(c < 96 || c > 105)) // 96~105 - 小键盘的0~9
|| e.shiftKey) { // Shift键,对应的code为16
prevent(e); // 阻止事件传播到keypress
}
}
}
$(function(){
$ (“input[name=‘text1’]”).keydown(function(e) {
digitInput($(this), e);
});
});

(2)限制input只能输入整型的整数:
function prevent(e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
function digitInput(e) {
var c = e.charCode || e.keyCode; //FF、Chrome IE下获取键盘码
if ((c != 8 && c != 46 && // 8 - Backspace, 46 - Delete
(c < 37 || c > 40) && // 37 (38) (39) (40) - Left (Up) (Right) (Down) Arrow
(c < 48 || c > 57) && // 48~57 - 主键盘上的0~9
(c < 96 || c > 105)) // 96~105 - 小键盘的0~9
|| e.shiftKey) { // Shift键,对应的code为16
prevent(e); // 阻止事件传播到keypress
}
}
$(function(){
$ (“input[name=‘text1’]”).keydown(function(e) {
digitInput(e);
});
});

(3)限制input只能输入保留小数点后一位的浮点数
function prevent(e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
function digitInput(el, e) {
var ee = e || window.event; // FF、Chrome IE下获取事件对象
var c = e.charCode || e.keyCode; //FF、Chrome IE下获取键盘码
var val = el.val();
var num = val.split(".");
if (c == 110 || c == 190){ // 110 (190) - 小(主)键盘上的’点’
(val.indexOf(".") >= 0 || !val.length) && prevent(e); // 已有小数点或者文本框为空,不允许输入点
} else {
if ((c != 8 && c != 46 && // 8 - Backspace, 46 - Delete
(c < 37 || c > 40) && // 37 (38) (39) (40) - Left (Up) (Right) (Down) Arrow
(c < 48 || c > 57) && // 48~57 - 主键盘上的0~9
(c < 96 || c > 105)) // 96~105 - 小键盘的0~9
|| e.shiftKey) { // Shift键,对应的code为16
prevent(e); // 阻止事件传播到keypress
}
else
{
if (num[1] != undefined)
{
if (num[1].length > 0 && c != 8 && c != 46)
{
prevent(e); // 阻止事件传播到keypress
}
}
}
}
}
$ (function(){
$ (“input[name=‘inp’]”).keydown(function(e) {
digitInput($(this), e);
});
});

猜你喜欢

转载自blog.csdn.net/qq_43772851/article/details/94718600