↑
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
isNotMax()
, which returns
true
when the maximum number
of characters hasn’t yet been reached or
false
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
maxlength
attribute. Note that even though
maxlength
isn’t a valid HTML
attribute for the
<textarea/>
element, you can still retrieve its value by using
getAttribute()
.
Next, the method call must be inserted into the text box’s
onkeypress
event handler. Remember, the
keypress
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
isNotMax()
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
maxlength
attribute, the method returns
true
, indicating that the
keypress
event should continue normally. As
soon as the maximum length has been reached, the method returns
false
, preventing the character
from being added to the text box.
This method can be used in conjunction with
FormUtil.tabForward()
to allow the same
skip ahead
functionality using
<textarea/>
elements.
You may be wondering why the code doesn’t use the standard
preventDefault()
method of the event object to block the
keypress
event. The simple answer is that
a bug in Mozilla’s handling of the
keypress
events causes
preventDefault()
to
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.
348
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 348
Free JavaScript Editor
Ajax Editor
©
→