Main Page

Tab forward automatically

<input type=”text” onfocus=”” />
<textarea onfocus=””></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 () {; };
for (var i=0; i < colTextAreas.length; i++){
colTextAreas[i].onfocus = function () {; };
This function starts by getting all instances of
in the document. The first
loop iterates through all the
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
event handler (optionally, you can use the
method). The second
loop does the same
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
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
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”) {
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 346

JavaScript EditorFree JavaScript Editor     Ajax Editor