When you visit Google.com, you probably noticed that the mouse cursor jumps to the searchbox, ready for users to type and submit a search. This method is called form focus. It’s made possible by using Javascript. With Javascript, you can set certain elements of the HTML form to be set in focus. This is particularly helpful for pages where there is minimal content, and the intent of the web developer/designer is to get the user to enter data and submit quickly. A login page is a perfect example of such a page.
You can bring into focus the username field, so users can start typing their login credentials. The form focus saves users from finding the mouse cursor on the screen, and then clicking on the field. With form focus, users are already on the form, ready to input text and submit. If the user presses Tab, the cursor jumps to the next field, which happens to be the password field. Pressing Enter, simply submits the form to start the login process. This article will show you the most simple way to add form focus to your HTML forms. Consider a login page. It has two fields: username, password, and a Submit button. The HTML markup is:
<form method="post' action="submit.php"> <label for="username">Username: </label> <input type="text" name="username" /> <label for="password">Password: </label> <input type="password" name="password" /> <input type="submit" name="submit" value="Login" /> </form> |
How To Add Focus To Forms
1. Assign an ID to the form. We are using an id of “login” in this example.
<form id="login" method='post' action="submit.php"> |
2. Add IDs to the fields.
<input id= "user" type="text" name="username" /> <input id= "pass" type="password" name="password" /> |
3. Add Tab Index to the fields. Notice the order starting with 1 and then 2.
<input id= "user" type="text" name="username" tabindex="1" /> <input id= "pass" type="password" name="password" tabindex="2" /> |
4. Add Javascript at the end of the form.
<script type=”text/javascript” language=”JavaScript”> document.login.user.focus(); </script> |
Where login is the id of the form, and user is the id of the field.
Final Form
<form id="login" method="post" action="submit.php"> <label for="username">Username: </label> <input id="user" type="text" name="username" tabindex="1" /> <label for="password">Password: </label> <input id="pass" type="password" name="password" tabindex="2" /> <input type="submit" name="submit" value="Login" /> </form> <script type="text/javascript" language="JavaScript"> document.login.user.focus(); </script> |
This is just one way of adding form focus to HTML forms. There are other methods, like using body onload and such, but I find this method the cleanest and the most simple one to implement by far.