↑
Main Page
Tab forward automatically
<input type=”text” onfocus=”this.select()” />
<textarea onfocus=”this.select()”></textarea>
It’s a small change, but it can provide big usability gains for users. If you want to apply this behavior
automatically to all text boxes on a screen, you can use the following function:
FormUtil.setTextboxes = function() {
var colInputs = document.getElementsByTagName(“input”);
var colTextAreas = document.getElementsByTagName(“textarea”);
for (var i=0; i < colInputs.length; i++){
if (colInputs[i].type == “text” || colInputs [i].type == “password”) {
colInputs[i].onfocus = function () { this.select(); };
}
}
for (var i=0; i < colTextAreas.length; i++){
colTextAreas[i].onfocus = function () { this.select(); };
}
};
This function starts by getting all instances of
<input/>
and
<textarea/>
in the document. The first
for
loop iterates through all the
<input/>
tags to find the text box and password fields (password
fields are text boxes, too). The function then adds an anonymous function containing the select code
to the field’s
onfocus
event handler (optionally, you can use the
EventUtil.addEventHandler()
method). The second
for
loop does the same
onfocus
assignment for all textareas on the page.
Tab forward automatically
When a text box can only accept a certain number of characters, wouldn’t it make sense to automatically
tab to the next field? This is done quite frequently when entering data such as social security numbers or
product ID numbers. This behavior is easy to mimic in JavaScript. This script requires that the
maxlength
attribute of the text box be used, such as:
<input type=”text” maxlength=”4” />
The basic idea is to determine when the maximum number of characters is entered into a text box and
then call the
focus()
method on the next field. To do this, another method is necessary:
FormUtil.tabForward = function(oTextbox) {
var oForm = oTextbox.form;
//make sure the textbox is not the last field in the form
if (oForm.elements[oForm.elements.length-1] != oTextbox
&& oTextbox.value.length == oTextbox.getAttribute(“maxlength”)) {
for (var i=0; i < oForm.elements.length; i++) {
if (oForm.elements[i] == oTextbox) {
for(var j=i+1; j < oForm.elements.length; j++) {
if (oForm.elements[j].type != “hidden”) {
oForm.elements[j].focus();
return;
346
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 346
Free JavaScript Editor
Ajax Editor
©
→