View Full Version : HTML form character counter
Weirfire
Apr 25th 2006, 5:03 am
I've got this Javascript function which stops you from typing any more than X characters but what I'd like to do is actually display the characters going up as the person types.
The url to what works now is www.weirfire.co.uk/form.php
and the code I've got so far is
<script language="JavaScript">
maxKeys = 100;
keysSoFar = 0;
alerted = false;
function keyup(what) {
keysSoFar++;
if (keysSoFar > maxKeys) {
if (!alerted) alert('That\'s enough!');
what.value = what.value.substring(0,maxKeys-1); // chop the last typed char
alerted = true;
}
}
</script>
<form>
<textarea cols=100 rows=20 onChange="change(this)" onKeyUp="keyup(this)"></textarea>
</form>
Weirfire
Apr 25th 2006, 5:27 am
okay I've found another solution
<script type="text/javascript">
function getObject(obj) {
var theObj;
if(document.all) {
if(typeof obj=="string") {
return document.all(obj);
} else {
return obj.style;
}
}
if(document.getElementById) {
if(typeof obj=="string") {
return document.getElementById(obj);
} else {
return obj.style;
}
}
return null;
}
function Counter(start,end,text,characters) {
var startObj=getObject(start);
var endObj=getObject(end);
var longitude=characters - startObj.value.length;
if(longitude <= 0) {
longitude=0;
text='<span class="disable"> '+text+' </span>';
startObj.value=startObj.value.substr(0,characters);
}
endObj.innerHTML = text.replace("{CHAR}",longitude);
}
</script>
<form action="#" method="post">
<table align="center" class="0" border="0" cellspacing="1" cellpadding="5">
<tr>
<td class="2">
<INPUT TYPE="TEXT" class="text" id="eBann" name="bannerURL" maxlength="100" size="60"
onKeyUp="Counter('eBann','sBann','{CHAR} characters left.',100);"><br>
<span id="sBann" class="minitext">100 characters left.</span></td>
</tr>
</table>
</form>
That seems to do the trick :)
exam
Apr 25th 2006, 5:41 pm
In the getObject function, if obj, is not a string, you should probably return obj and not obj.style
Weirfire
Apr 26th 2006, 4:47 am
Thanks for the tip D :)
exam
Apr 26th 2006, 7:05 am
No prob. You could also add some more cross-browser compatibility by including document.layers to the function as exemplified here: http://www.webcodingtech.com/javascript/get-object-by-id-compatible.php
Weirfire
Apr 26th 2006, 9:18 am
Now you're just showing off! :P
exam
Apr 26th 2006, 9:23 am
Showing off would be giving you this link http://www.webcodingtech.com/javascript/limit-input-text.php
kashem
Apr 26th 2006, 9:30 am
thanks guys I was in need of such code
Weirfire
Apr 26th 2006, 4:42 pm
You're welcome kashem. Donations are welcome! ;)
vBulletin® v3.8.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.