Main Page

Focus on the first field

//is the form property equal to oForm?
alert(oField1.form == oForm); //outputs “true”
These properties, methods, and events can come in handy when advanced functionality is needed, such
as when you want to move the focus to the first field.
Focus on the first field
When a form is displayed on a Web page, the focus is typically not on the first control. It’s easy to
change this with a generic script that can be used on any form page.
Many developers just put the following in the page’s
event handler:
This works in most situations, but consider the problem when the first element in the form is a hidden
field, an element that doesn’t support the
method. In this case, you’d be greeted with a JavaScript
error. The key is to set the focus to the first visible form field, and you can write a short method for that.
All the methods pertaining to forms in this chapter are written to an object called
for easy
var FormUtil = new Object;
object is only intended to keep similar functions grouped together; you may choose to
provide these methods in a separate object or on their own.
The method to set the focus on the first field first checks to ensure that a form exists on the page. It does
this by checking the value of
FormUtil.focusOnFirst = function () {
if (document.forms.length > 0) {
After you know at least one form is present, you can start to iterate through the form fields until you
find the first one that isn’t hidden.
FormUtil.focusOnFirst = function () {
if (document.forms.length > 0) {
for (var i=0; i < document.forms[0].elements.length; i++) {
var oField = document.forms[0].elements[i];
if (oField.type != “hidden”) {
Hidden fields only support the
property, but none of the methods or events
common to form fields.
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 339

JavaScript EditorFree JavaScript Editor     Ajax Editor