Word And Character counter JS
When you have a text area field where you need to provide information about the
word count when the user enters some text in the field. Length of the
field is supposed to be 50 Characters. Initially it would show 50 characters left.
Only 50 characters
allowed!
characters left
characters left
<SCRIPT LANGUAGE="JavaScript"> function CountLeft(field, count, max) { if (field.value.length > max) field.value = field.value.substring(0, max); else count.value = max - field.value.length; } </script> <center> <form name=sample action=""> Only 50 characters allowed!</br> <textarea rows="15" name="text" cols="45" onKeyDown="CountLeft(this.form.text,this.form.left,50);" onKeyUp="CountLeft(this.form.text,this.form.left,50);"></textarea> <input readonly type="text" name="left" size=3 maxlength=3 value="50"> characters left</font> </form> </center> |
Counting the number of words in a text area is quite simple with JavaScript. The idea is to count the number of spaces and use this to calculate the number of words. The following example illustrates the script.
<script> function cnt(w,x){ var y=w.value; var r = 0; a=y.replace(/\s/g,' '); a=a.split(' '); for (z=0; z<a.length; z++) {if (a[z].length > 0) r++;} x.value=r; } </script> <form name="myform"> <textarea rows="15" name="w" cols="45" onkeyup="cnt(this,document.myform.c)"></textarea> <br />Word Count: <input type="text" name="c" value="0" size="5" onkeyup="cnt(document.myform.w,this)" /> </form> |
No comments:
Post a Comment