JavaScript: Form Field Focus


Introduction

Author: Martin Warning
Year: 2007
License: Free

It adds to the usability of a site if the first field on a form or the site search field receives focus on page load. This way the user can start typing without first selecting the field. For this we use the JavaScript event onload in the <body> element. As a word of warning this can also be annoying feature for the user. When the user starts typing in the location bar of the browser or in another form field before the page finished loading the focus will be taken away when the page finishes loading. Especially when the user sets a page as their default browser start page this can be an annoying feature.

Code

Languages: The following code is an example field focus on page load:
<body onload="document.frmSearch.strSearch.focus();">

<form name="frmSearch">
	<input type="text" name="strSearch" />
</form>

We use the following format to give focus to the field. First we go to the document.formname.fieldname and then we use focus() to give the field focus.



Pinternet.net: The world of beer on the Internet
Printed from: http://flyinglowlander.com/ (5/20/2012)
© FlyingLowander.com 2006 - 2012

Visit http://flyinglowlander.com for more XHTML, CSS, ASP and JavaScript examples, templates and tutorials.