Focus In Specific Form Field On Page Load
When a web page with a form loads in a browser, a specific form field can obtain keyboard focus. Ready to type. So you don't have to click into it first.
This article is for implementing the functionality equally for all popular browsers, even IE, regardless which HTML version is used. It does require JavaScript.
(As of this writing, IE does not support HTML5. HTML5 has a new form attribute named "autofocus" to automatically give a specific form field focus when the page loads.)
Example implementation
This example puts keyboard focus on the second form field:
The above form field will have obtained focus when the web page loaded.
Implementing auto form field focus on page load
To implement, the form field to automatically obtain focus needs to have an id. Some JavaScript is run when the page is loaded, which gives the form field its focus.
Here is an example form field with an id.
<input type="text" id="field-id" name="field_name">
And here is the JavaScript.
<script type="text/javascript"> // Specify the id value of the form field to automatically // obtain focus when the page loads. var FieldID = "field-id" // End of customization document.getElementById(FieldID).focus(); </script>
Where to put the JavaScript
Put the JavaScript somewhere below the form so the JavaScript runs after the form source code is loaded in the browser. It can be immediately below the form or at the end of the page next to the cancel </body> tag.
Example implementation source code
Here is the complete source code for the above example implementation.
<form onsubmit="return false;"> <input type="text" id="field-id1" name="field_name1" style="width:200px;"><br> <input type="text" id="field-id2" name="field_name2" style="width:200px;"><br> <input type="text" id="field-id3" name="field_name3" style="width:200px;"> </form> <script type="text/javascript"> // Specify the id value of the form field to automatically // obtain focus when the page loads. var FieldID = "field-id2" // End of customization document.getElementById(FieldID).focus(); </script>
That's the simplicity of it.
With HTML5, it's even simpler. Just put autofocus="autofocus" into the form field to get the focus, instead of the above implementation instructions. (See HTML5 input autofocus Attribute for HTML5 "autofocus" info.)
If it is important that your web page has the form field focus functionality in all browsers, implement it according to this article.
Bookmark this article or put it on your twitter feed or favorite it, whatever you do to keep track of information you may need to refer to later on.
Will Bontrager