count words in <textarea>
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.
jonsteele posted this at 23:57 — 1st February 2001.
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 posted this at 07:57 — 2nd February 2001.
They have: 410 posts
Joined: Oct 1999
well, yes, i could. if i only knew how to do that... i don't know java this good. could anyone help me out?
jonsteele posted this at 21:00 — 2nd February 2001.
They have: 21 posts
Joined: Nov 2000
Try this:
<script>
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);
</script>
Jon.
Jon Steele -
EverySolution.com
merlin posted this at 14:43 — 5th February 2001.
They have: 410 posts
Joined: Oct 1999
yep, that worked
i had to modify the code a little bit:
<script LANGUAGE="JavaScript">
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;
}
</script>
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.