Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Counting words in a textarea --- how? 1

Status
Not open for further replies.

ChetN

Technical User
Feb 9, 2001
42
US
I have an essay question that requires 100 words or more. I can get it to count correctly IF the student does not use separate paragraphs. The input onChange passes the value as the variable words.

The problem: If there are separate paragraphs the count is off by one for each of the paragraphs. My code:

var countWords=0;
function numWords(words){
//the replace deletes any double spaces that most typists use to separate sentences. Double spaces create two commas when the split occurs.

words=words.replace(". ", ". ");
var ttcnt=words.split(" ");
countWords=ttcnt.length;
}

The input:

<TEXTAREA Rows=&quot;10&quot; Cols=&quot;65&quot; name=&quot;16&quot; id=&quot;Q16&quot; onchange=&quot;numWords(this.value)&quot;>Introduction.</TEXTAREA>

 
Try this way:
Code:
<script>
//function to see if a character is a full-stop, comma
//colon, semicolon, carriage-return or newline
//ie any character that signifies the end of a word
function isEndWord(testChar){
 var wordBreakChars = new Array(13,10,44,46,59,58,32);
 var retval=false;
 for(a=0; a<wordBreakChars.length; a++){
  if(wordBreakChars[a] == testChar.charCodeAt(0)){
   retval = true;
  }
 }
 return retval;
} 

//function to loop through a string and count the number
//of words present.
function countwords(textstr){
 var currword = '';
 var wordcount = 0;
 for(b=0; b<textstr.length; b++){
  if(isEndWord(textstr.charAt(b))){
  //if the current character is an 'endword'
   if(currword != ''){
    //and we are currently on a word
    //increment the wordcount and
    //set the current word back to nothing
    wordcount++;
	currword = '';
   }
  }
  else{
   //if we are not on an endword character
   //add the character to the current word
   currword = currword + textstr.charAt(b);
  }
 }
 if(currword != ''){
  //if we end the string without closing off our
  //last word - increment the word count
  wordcount++;
 }
 return wordcount;
}
   
</script>
And call the function from your textarea like so:
Code:
<TEXTAREA Rows=&quot;10&quot; Cols=&quot;65&quot; name=&quot;16&quot; id=&quot;Q16&quot; onchange=&quot;alert('Word Count: ' + countwords(this.value))&quot;>Introduction.</TEXTAREA>
 
also i'd suggest that instead of incorporating it into the onchange event of the TEXTAREA, you count them once at the end ?

so if its part of a form, add it to the onsubmit event of the form and only let them submit if they have 100 words or more in the textarea.
 
Interesting point, and probably a good excuse for me to drag the whole thread horribly off topic. When, in the sequence of events is the best time for form validation. I personally prefer to be told straight away - rather than thirty questions down the track - that I entered my DOB in dd/mm/yyyy format when the form was expecting mm/dd/yyyy format.

Field based validation lets the user know straight away when an invalid value has been entered. Thus allowing them to correct it straight away, rather than having to scan through the entire looking for the field after completing it. Additionally, I'm sure we've all filled in forms where on pressing the submit button we get one error message, go change that field, press submit, get another error message, go change that field etc. Very annoying.

Field based validation is easier to code as well. Instead of having a mammoth validation function for the entire form (which usually means fieldnames are hard-coded into the function), you can usually code the validation script for each field directly into the field declaration (referencing the 'this' object) - very useful if you then need to copy and paste selected fields into a different form.

Anyone else got an opinion about this?
 
DwarfThrower,
Thank you very much. Your coding works like a charm. I really like the added comments--they walked me thru the logic. I am new to this Javascript game and welcome all the help I can get. Star for you.

Clarkin,
I appreciate the tips and have implemented them as well.
 
good points dwarfthrower -

what I was trying to suggest was that the 100 word validation be done once (once the student has decided their essay is finished) rather than every time they type a character into the textarea.

So, if you like having all your validation logic in one place, stick it at the end. If you like the field by field approach - instead of using the form's onSubmit event, use the text area's onBlur event (triggered when the user makes their browser leave the text area.. say by clicking, tabbing or trying to submit the form).

The reason I suggest it was that your original function counted the words every time the text area value changed (using onChange) which could conceivably slow things down as it looped through all the text :)

Also, if you have sorted out your code to work well for you - post it up for posterity :) lots of people search here with similar problems but never post a question..

Colm
 
&quot;what I was trying to suggest was that the 100 word validation be done once (once the student has decided their essay is finished) rather than every time they type a character into the textarea.&quot;

The onChange event only fires if the user leaves the textarea and the content has changed, as opposed to the onBlur event, which fires every time the user leaves the field, regardless of whether the contents have changed or not. Try it and see.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top