This javascript function counts the number of remaining characters in a given input element and trims the string if the length is bigger that the maximum allowed value.
Code for Javascript text counter:
<html>
<head>
<title>Java script text counter</title>
<script language="javascript" type="text/javascript">
function charCounter(element,length,counterField,counterType){
if(element != null){
if(counterType == 'increment'){
counterField.value = element.value.length;
}else{
if(element.value.length > length)
element.value = element.value.substring(0,length);
else
counterField.value = length - element.value.length;
}
}
}
</script>
</head>
<body>
<div>
<textarea id="txtDescription" name="Description" onkeyup="javascript:charCounter(this,50,txtCounter,'');" onkeydown="javascript: charCounter(this,50,txtCounter,'')" rows="3" cols="30"></textarea>
</div>
<div>
<input readonly="readonly" name="txtCounter" id="txtCounter" size="4" maxlength="4"
value="0" type="text" /> characters left
</div>
</body>
</html>
<head>
<title>Java script text counter</title>
<script language="javascript" type="text/javascript">
function charCounter(element,length,counterField,counterType){
if(element != null){
if(counterType == 'increment'){
counterField.value = element.value.length;
}else{
if(element.value.length > length)
element.value = element.value.substring(0,length);
else
counterField.value = length - element.value.length;
}
}
}
</script>
</head>
<body>
<div>
<textarea id="txtDescription" name="Description" onkeyup="javascript:charCounter(this,50,txtCounter,'');" onkeydown="javascript: charCounter(this,50,txtCounter,'')" rows="3" cols="30"></textarea>
</div>
<div>
<input readonly="readonly" name="txtCounter" id="txtCounter" size="4" maxlength="4"
value="0" type="text" /> characters left
</div>
</body>
</html>
Demo:
characters left
0 comments
Post a Comment