Navigation:    Home arrow Text Box Characters Counter
Javascript Text Box Characters Counter PDF  
Digg Reddit Ma.gnolia Stumble Upon Facebook Twitter Google Yahoo! MyWeb Furl" BlinkList Technorati Mixx Bookmark

Forms always require validation when they are used in not safe environments. One method is to verify the data submitted through POST or GET before actually executing the form action. Using Javascript it is possible to do this in a more simple way.

Here you have an example of how you can limit the number of characters an user can insert into a input or a textarea field.

You can see here a running javascript count words script

The right field keeps track of how many characters a user can still insert and the characters that overtake that limit are removed.

The code explained: We create a javascript function that counts the number of remaining characters and trims the string if the length is bigger that the maximum allowed value.

he form will contain an input field for the text and one for the remaining number of characters.

he text input field will call the javascript function every time a up or down key event will arrise.

See the code below:

  <SCRIPT LANGUAGE="JavaScript">
// function parameters are: field - the string field, count - the field for
// remaining characters number and max - the maximum number of
// characters

function CountLeft(field, count, max) {
// if the length of the string in the input field is greater than the max value,
// trim it

if (field.value.length > max)
field.value = field.value.substring(0, max);
else
// calculate the remaining characters
count.value = max - field.value.length;
}
</script>

<center>
<form name=sample action="">
<font size="1" face="arial, helvetica, sans-serif"> Only 50 characters
allowed!
// at every key up and key down event the upper function is called
<input name="text" type="text" size="40"
onKeyDown="CountLeft(this.form.text,this.form.left,50);"
onKeyUp="CountLeft(this.form.text,this.form.left,50);">
<input readonly type="text" name="left" size=3 maxlength=3
value="50">
characters left</font>
</form>
</center>

If you found this tutorial useful you might be interested to read the following:

Installing Apache, PHP, MySQL on a Windows 98/2000/XP Computer
PHP Form image verification
PHP Create Image Thumbnail
PHP Form Image Upload
PHP print random image from a folder