注意: charCode
是非标准且已弃用的,而 keyCode
仅仅是已弃用的。
请检查以下代码
JavaScript
<script>
function check(e,value)
{
var unicode=e.charCode? e.charCode : e.keyCode;
if (value.indexOf(".") != -1)if( unicode == 46 )return false;
if (unicode!=8)if((unicode<48||unicode>57)&&unicode!=46)return false;
}
function checkLength()
{
var fieldLength = document.getElementById('txtF').value.length;
if(fieldLength <= 4){
return true;
}
else
{
var str = document.getElementById('txtF').value;
str = str.substring(0, str.length - 1);
document.getElementById('txtF').value = str;
}
}
以下是带有 number
类型的 HTML input
onInput //Is fired also if value change from the side arrows of field in Chrome browser
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength()" />
演示示例
更新 -- 更通用的代码示例
将上述函数更改为以下内容
function checkLength(len,ele){
var fieldLength = ele.value.length;
if(fieldLength <= len){
return true;
}
else
{
var str = ele.value;
str = str.substring(0, str.length - 1);
ele.value = str;
}
}
在HTML中这样使用
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength(4,this)" />
<input type="number" onKeyPress="return check(event,value)" onInput="checkLength(5,this)" />
<input type="number" onKeyPress="return check(event,value)" onInput="checkLength(2,this)" />
Demo