count words in <textarea>

merlin's picture

They have: 410 posts

Joined: Oct 1999

i need a script, that counts the words that a user puts in a < textarea >< /textarea >-form-tag. the number of words should be displayed in another form-field (< input type=text > ) .
i have a solution that counts the chars, but how do i get the words?
huh, the whole thing will be in java-script i suppose? thanks for any help.

They have: 21 posts

Joined: Nov 2000

Couldn't you count the " " (whitespace) then add 1 to get number of words? Just a thought.

Jon.

merlin's picture

They have: 410 posts

Joined: Oct 1999

well, yes, i could. if i only knew how to do that... Sad i don't know java this good. could anyone help me out?

They have: 21 posts

Joined: Nov 2000

Try this:

&lt;script&gt;
string = document.form_name.textarea_name.value;

//creates array "words" by splitting string where there is whitespace
words = string.split(" ");

//counts words
document.write(words.length);
&lt;/script&gt;
'
Jon.

Jon Steele -
EverySolution.com

merlin's picture

They have: 410 posts

Joined: Oct 1999

yep, that worked Laughing out loud
i had to modify the code a little bit:

&lt;script LANGUAGE="JavaScript"&gt;
function CharLeft(target) {
var maxLength = 81;
string = document.wettbewerb.story.value;
words = string.split(" ");

if (target.value.length > maxLength) {
target.value = target.value.substring(0,maxLength);
charleft = 0;
} else {
charleft = maxLength - words.length;
}
document.wettbewerb.msg_len.value = charleft;
}
&lt;/script&gt;
'

and

<textarea name="story" rows=3 cols=45 onChange=CharLeft(this) onFocus=CharLeft(this) onKeyDown=CharLeft(this) onKeyUp=CharLeft(this)></textarea><br>
<input value=80 size=3 name="msg_len" readonly><br>
'
like this, it's writing the number of words left directly into the form-field.
thanks jon for your help!

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.