限制用户输入不符合规范的数字与小数点导致不好计算价格问题,特整理了下面的代码,需要的朋友可以参考下。
<html>
<head>
<title>text 数字</title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
</head>
<script type="text/javascript">
function check(event) {
var e = window.event || event;
var target = e.srcElement || e.target;
var k = e.keyCode;
if(isFunKey(k)) {
return true;
}
var c = getChar(k);
if(target.value.length == '' && (c == '-' || c == '+')) {
return true;
}
if(isNaN(target.value + getChar(k))) {
return false;
}
return true;
}
function isFunKey(code) {
// 8 --> Backspace
// 35 --> End
// 36 --> Home
// 37 --> Left Arrow
// 39 --> Right Arrow
// 46 --> Delete
// 112~123 --> F1~F12
var funKeys = [8, 35, 36, 37, 39, 46];
for(var i = 112; i <= 123; i++) {
funKeys.push(i);
}
for(var i = 0; i < funKeys.length; i++) {
if(funKeys[i] == code) {
return true;
}
}
return false;
}
function getChar(k) {
if(k >= 48 && k <= 57) {
return String.fromCharCode(k);
}
if(k >= 96 && k <= 105) {
return String.fromCharCode(k - 48);
}
if(k == 110 || k == 190 || k== 188 ) {
return ".";
}
if(k == 109 || k == 189) {
return "-";
}
if(k == 107 || k == 187) {
return "+";
}
return "#";
}
</script>
<style type="text/css">
textarea {
width: 200px;
height: 80px;
}
span {
color: #ff0000;
}
</style>
<body>
<input style="ime-mode:disabled;" onpaste="return false" onkeydown="return check(event)" onkeyup="if(isNaN(this.value)||this.value<0||this.value>59) this.value='0'">
</body>
</html>
text 数字