Main Page

Limit textarea characters

method takes one argument, the text box to check. Inside the method, a
reference to the owning form is extracted by using the text box’s
property. Next, the method checks
to see if the text box is the last element in the form by comparing it to the element in the last position. If
the text box passes this test, it is then tested to see if it has reached the maximum number of allowable
characters by using the text box’s
attribute. If the text box doesn’t have the maximum num-
ber of characters yet, the method exits quietly; otherwise, the first loop is entered.
The first
loop’s sole purpose is to locate the text box in the
collection. When it is
found, a problem similar to the one encountered in the previous section pops up: What if the next ele-
ment is a hidden field? That’s where the second loop comes in, as it iterates up through the remaining
form elements until it finds the first non-hidden field. When that field is found, the user focus is set to it,
and the method is exited via the
This method must be called after each character has been entered into the text box, so you need to use
event handler (the
event, you may recall, fires after the character has been placed
into the text box; the
event fires before):
<input type=”text” maxlength=”4” onkeyup=”FormUtil.tabForward(this) “ />
Note that the
keyword is being used to pass into the method a pointer to the text box. Suppose you
want the user to enter a U.S.-format phone number (three digits, three digits, four digits). You could cre-
ate three text boxes like this:
<input type=”text” id=”txtAreaCode” maxlength=”3”
onkeyup=”FormUtil.tabForward(this)” />
<input type=”text” id=”txtExchange” maxlength=”3”
onkeyup=”FormUtil.tabForward(this)” />
<input type=”text” id=”txtNumber” maxlength=”4”
onkeyup=”FormUtil.tabForward(this)” />
As soon as the user finishes entering the numbers in one text box, the focus moves to the next, so the
user never has to use the Tab key or the mouse to move between fields.
Limit textarea characters
Although the
element text boxes can easily limit the number of characters allowed, the
elements cannot do this because they do not have a
property. The solution is
to create some JavaScript to mimic the
property. Ultimately, you want to be able to do the
<textarea rows=”10” cols=”25” maxlength=”150”></textarea>
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 347

JavaScript EditorFree JavaScript Editor     Ajax Editor