Auto focus ‘first visible’ form field on page…

Occassionally there comes a need to set the focus within a web page to the first ‘visible’ form field, here’s the most convenient I’ve found thus far…

Implementation:
1. Add the following Javascript to the HEAD section of your page.

function formfocus() {
if(document.forms.length > 0)
{
var formElements = ["text", "checkbox", "radio", "select-one", "select-multiple", "textarea"];
var form = document.forms[document.forms.length-1];
for (var j = 0; j < form.elements.length; j++)
{
var field = form.elements[j];
for(var x = 0; x < formElements.length; x++)
{
if (field.getAttribute("type") == formElements[x])
{
field.focus();
return false;
}
}
}
}
}

2. Add the function call to the BODY tag…

<body onload="formfocus();">

That’s it! Enjoy!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.