HTML / JavaScript: Focus user on first available field
January 22nd, 2007
So far I haven’t figured out where is the user’s caret when entering an HTML page with multiple fields.
With the following code (placed right before the closing HTML tag), the page will load and focus the first text or text area field on the page.
<script>
for(i=0; i<document.forms[0].elements.length; i++) {
felement = document.forms[0].elements[i];
if (felement.type == 'text' || felement.type == 'textarea') {
felement.focus(); break;
}
}
</script>
The beauty of the code is that it won’t matter the name of the form or field, giving enough flexibility to use the same JavaScript code on all the pages that have fields in your application.
Notes:
- Different types of fields can be used to receive focus changing the if condition.
- Change the form’s index to the one containing the field that should receive the focus, it currently checks the fields on the first form (index starting at 0).
Entry Filed under: JavaScript
Leave a Comment
You must be logged in to post a comment.
Trackback this post | Subscribe to the comments via RSS Feed