faqts : Computers : Programming : Languages : JavaScript : Forms : TextAreas/TextFields

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

13 of 61 people (21%) answered Yes
Recently 3 of 10 people (30%) answered Yes

Entry

Is there a way to count the number of words in a TextArea or TextField?
Is there a way to change the value of input=text element without modifying the cursor (caret?) posit
Is there a way to test the value of a input=text element and avoid bad values. (onkeyup misses keyre

Oct 7th, 2001 09:10
Olivier LAHAYE, Bob Foster,


The following function should be an elegant way do the job (tested with 
IE6)
It should also work with Konqueror 2.2.1 (with the libpcre for regexp)

The method is the following: I'm using the match method to match non 
empty words. This method returns a table of all matched entries.

The number of words is the length of the table or 0 if no match is 
found (the match method returns null instead of a table)

Note the "+" sign in the regexp, otherwise, the "\w" can match the 
empty word "" (it can match 0 words).

In the header add this:
<SCRIPT language="JavaScript1.3">
function countWords(obj) {
	matchTable=obj.value.match(/\w+/g);
	alert(matchTable?matchTable.length:0);
}
</SCRIPT>

And in the body add this:
<INPUT type="text" name="WORDS" onchange="countWords(this);">

not tested with other browsers.
This function needs:
  - that the string object has a match function that returns an array 
of matched instances found.
  - that the browser javascript engine supports regexps ("\w" to match 
a word and "g" for globally).

--
    Olivier LAHAYE