Main Page

Explorer, Safari, Opera, as well as Mozilla

This is the first method of the chapter dealing directly with text boxes (the previous sections have had
methods that work between text boxes and the rest of the form), and so it is time for a new wrapper
object to encapsulate the coming methods:
var TextUtil = new Object();
The first method for this object is called
, which returns
when the maximum number
of characters hasn’t yet been reached or
if it has. The reasoning for this is explained in a moment.
First, take a look at the code:
TextUtil.isNotMax = function(oTextArea) {
return oTextArea.value.length != oTextArea.getAttribute(“maxlength”);
As you can see, this method is very simple: just an equality comparison between the length of the text
in the text box and the
attribute. Note that even though
isn’t a valid HTML
attribute for the
element, you can still retrieve its value by using
Next, the method call must be inserted into the text box’s
event handler. Remember, the
event fires before a character is inserted into the text box, which is exactly what you must
stop to enforce the maximum character limit. Here’s what the code looks like:
<textarea rows=”10” cols=”25” maxlength=”150”
onkeypress=”return TextUtil.isNotMax(this)”></textarea>
Notice that the return value of
is being returned to the event handler. This is an older
way of preventing the default behavior for an event. When the text length is less than the
attribute, the method returns
, indicating that the
event should continue normally. As
soon as the maximum length has been reached, the method returns
, preventing the character
from being added to the text box.
This method can be used in conjunction with
to allow the same
skip ahead
functionality using
You may be wondering why the code doesn’t use the standard
method of the event object to block the
event. The simple answer is that
a bug in Mozilla’s handling of the
events causes
malfunction. In order to make this a truly cross-browser solution, the faulty function-
ality had to be eliminated. The code in this example works in all DOM-compliant
browsers, including Internet Explorer, Safari, Opera, as well as Mozilla.
You add extra attributes frequently in this chapter; however, if you are using the
strict implementation of XHTML, the page is considered invalid if it contains an
unexpected attribute. Depending on your specific requirements, it may be necessary
to add a JavaScript property to the element’s DOM node or to pass in the extra infor-
mation directly to a function instead of using the attribute in HTML.
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 348

JavaScript EditorFree JavaScript Editor     Ajax Editor