Note: charCode
is non-standard and deprecated, whereas keyCode
is simply deprecated.
Check this code
JavaScript
<script>
function check(e,value)
{
//Check Charater
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;
//Suppose u want 4 number of character
if(fieldLength <= 4){
return true;
}
else
{
var str = document.getElementById('txtF').value;
str = str.substring(0, str.length - 1);
document.getElementById('txtF').value = str;
}
}
and HTML input
with number
type below
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()" />
Fiddle Demo
Update -- Little bit generic code example
Change above function into this one
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;
}
}
In HTML use like this
<!-- length 4 -->
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength(4,this)" />
<!-- length 5 -->
<input type="number" onKeyPress="return check(event,value)" onInput="checkLength(5,this)" />
<!-- length 2 -->
<input type="number" onKeyPress="return check(event,value)" onInput="checkLength(2,this)" />
Demo
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…