Published on: 2006-05-06 - Views: 10119

Digg! del.icio.us Furl reddit spurl bloglines ma.gnolia.com Yahoo MyWeb technorati blogmarks blinklist pixelgroovy Share this tutorial on tutorialicio.us! simpy
If you are setting up a form on your website you might want to limit the length of the text that your users can type in a textarea so they can't send you a poem for you to read.
HTML doesn't offer such a feature, but we can use javascript to check the text length and in case trim it. The user will also be shown the number of remaining chars.
We need to write a function that, each time that the user types a char, counts the number of chars and removes those exceeding the limit.
We'll use this function: it checks the lenth of the textarea content and if it's longer than the allowed limit, it trims the text to the chosen length.
As usual with Javascript put it into your HEAD section or in your external .js file
<script language="Javascript" type="text/javascript">
function countAreaChars(areaName,counter,limit)
{
if (areaName.value.length>limit)
areaName.value=areaName.value.substring(0,limit);
else
counter.value = limit - areaName.value.length;
}
</script>
Then, in your HTML page you must use the following lines:
Each time that a key is pressed the script checks the message length (trimming it if necessary) and sets the actual number of remaining chars so it canbe displayed in the leftChars field.
<form name=formName action="yourscript.php">
<textarea name=feedback cols=45 rows=6
onKeyDown="countAreaChars(this.form.feedback,this.form.leftChars,400);"
onKeyUp="countAreaChars(this.form.feedback,this.form.leftChars,400);">
</textarea>
<input type=text name=leftChars readonly size=3 maxlength=3 value="400"> chars left
</form>
You should obviously customize the values and the fields' names to make the form fit your page, in this example there are 400 allowed chars.