在 tex 框的 onkeypress 或 onkeyup 事件上尝试下面的 javascript 函数
像这样打电话onkeypress = "return (event,'txtid',9,2)"
beforelength
是在'。'之前。允许多少个数字,afterLength
用于“。”之后 号码长度
function isNumberKey(event, obj, beforeLength, afterLength) {
var keyCode1 = event.keyCode;
var keyCode = 0;
if (keyCode1 == 0)
keyCode = event.which;
else {
keyCode = keyCode1;
}
// alert(keyCode);
// alert(keyCode1);
if ((keyCode >= 48 && keyCode <= 57) || keyCode == 46 || keyCode == 13 || keyCode == 27 || keyCode == 127) {
var text = document.getElementById(obj).value;
if (keyCode == 46 && keyCode1 == 0) {
if (text.toString().indexOf(".") != -1) {
return false;
}
}
if (keyCode == 46) {
if (text.toString().indexOf(".") != -1) {
return false;
}
}
// if (!/^\d{0,10}(?:\.\d{0,2})?$/.test(text)) {
// return false;
// } else {
// }
var splitText = text.split('.');
if (splitText[0].length >= beforeLength) {
if (keyCode == 46 && text.toString().indexOf(".") == -1) {
return true;
} else if (text.toString().indexOf(".") != -1) {
return true;
}
return false;
}
// if (splitText.length > 1 && splitText[1].length == afterLength) {
// return false;
// }
}
else {
return GetDefault(event);
}
return true;
}
function GetDefault(event) {
var keyCode = event.keyCode;
if (keyCode == 0)
keyCode = event.which;
if (keyCode == 8 || keyCode == 9 || keyCode == 35 || keyCode == 36 || keyCode == 37 || keyCode == 38 || keyCode == 39 || keyCode == 40 || keyCode == 46 || keyCode == 118) {
return true;
}
return false;
}