Wednesday, May 13, 2009

How to limit the text length as maximum with Javascript (Text Counter)

Here is the javascript text counter. When you write down the character in Textarea box, it show the available text count immediately and remove the extra text as well. Put the following javascript between <head> and </head> tag.
<script type="text/javascript">
function textCounter(field, countfield, maxlimit)
{
    if (field.value.length > maxlimit)
        field.value = field.value.substring(0, maxlimit);
    else
        countfield.value = maxlimit - field.value.length;
}
</script>
Here is form tag.
<form>
<span>Comments:</span>
<span>Only 200 char allowed</span>
<textarea id="comment" onblur="this.style.backgroundColor='#ffffff'" onfocus="this.style.backgroundColor='#FFFCF9'" onkeyup="textCounter(comment,textCount,200);" onkeydown="textCounter(comment,textCount,200);" rows="7" cols="60" name="comment" style="background-color: rgb(255, 255, 255);">
</textarea>
<input type="text" value="200" maxlength="3" size="3" id="textCount" name="textCount"/>
<span>Char count</span>
</form>

That's it. Enjoy the JScript!

No comments:

Post a Comment