By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,935 Members | 1,545 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,935 IT Pros & Developers. It's quick & easy.

word counter

P: n/a
Hello, can anybody share the code for a word counter for the textarea
user input? what if max characters are 256?

thanks
Jul 20 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
reneecccwest wrote:
Hello, can anybody share the code for a word counter for the textarea
user input? what if max characters are 256?

thanks


Assuming a "word" is any sequence of non-whitespace characters surrounded
by whitespace, the following will count the words in a text area:

<form>
<textarea name="myTextarea"></textarea>
<input type="button" name="myButton" value="Count words"
onclick="countWords(this.form.myTextarea.value);">
</form>
<script type="text/javascript">
function countWords(s) {
var words = s.split(/\s+/);
alert(words.length);
}
</script>

For preventing entry of more then 256 characters, you can use the
following. Be aware you should provide server-side validation as well,
since the client-side prevention shown below can easily be circumvented:

<textarea name="myTextarea" onkeydown="return maxChars(this,
256);"></textarea>
<script type="text/javascript">
function maxChars(ta, count) {
return (ta.value.length < count);
}
</script>

--
| Grant Wagner <gw*****@agricoreunited.com>

* Client-side Javascript and Netscape 4 DOM Reference available at:
*
http://devedge.netscape.com/library/...ce/frames.html

* Internet Explorer DOM Reference available at:
*
http://msdn.microsoft.com/workshop/a...ence_entry.asp

* Netscape 6/7 DOM Reference available at:
* http://www.mozilla.org/docs/dom/domref/
* Tips for upgrading JavaScript for Netscape 7 / Mozilla
* http://www.mozilla.org/docs/web-deve...upgrade_2.html
Jul 20 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.