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);
        countfield.value = maxlimit - field.value.length;
Here is form tag.
<span>Only 200 char allowed</span>
<textarea id="comment" onblur="'#ffffff'" onfocus="'#FFFCF9'" onkeyup="textCounter(comment,textCount,200);" onkeydown="textCounter(comment,textCount,200);" rows="7" cols="60" name="comment" style="background-color: rgb(255, 255, 255);">
<input type="text" value="200" maxlength="3" size="3" id="textCount" name="textCount"/>
<span>Char count</span>

That's it. Enjoy the JScript!

No comments:

Post a Comment