Home / Using Javascript to focus a form element onload

Using Javascript to focus a form element onload

The Personalised Plates website has a big input box on every page for searching for available personalised plates. The page template uses the Javascript form element focus() function to set the focus on this text box when the page loads so the user can start to type in a personalised plate idea without having to click the box with their mouse.

Originally we simply had this in the <body> tag's onload property like so, where "searchForm" is the name of the form the search box is in, and "legend" is the name of the input box:

body onload="document.searchForm.legend.focus();"

The only problem with doing this is that the input text box only gets focus once the page has completed loading. If the page had a second form on it, eg for sending an enquiry through, then the user might start typing their details into the enquiry form while the page is still loading, only to have the focus suddenly transferred back to the search box. This is fairly annoying so a solution was required.

Instead of calling the focus() function directly from the onload property of the <body> tag, onload now calls a separate function. This function tests to see if the "searchForm" form is present on the page, and if there is less than 2 forms on the page. If both these conditions are true, then the focus is set to the search box.

The Javascript function for doing this looks like so:

function setfocus() {

  if(document.forms.length < 2 && document.searchForm) {
    document.searchForm.legend.focus();
  }
}

The document.forms.length < 2 could also be document.forms.length == 1; either way will work the same.

Now the <body> tag looks like this:

body onload="setfocus();"

Now if there is more than one form on the page, focus isn't stolen from it if the user is currently typing text into one of the boxes.