|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionI was developing a web application that had some pretty complex authorization logic, and would enable and disable certain inputs on many different web forms. For example, user A would have the first 5 text boxes disabled and user B would have text boxes 5 through 10 disabled. That made it difficult to set the focus to the proper input. Difficult in terms of the amount of code required to accomplish such a simple task. Options
A Few TriesSince duplicating logic is generally agreed to be a bad practice, I went for the dynamic option. My first idea was to simply set the focus to the first element of the first form, which would work in some instances and not in others. For example, in a .NET application the first element of the first form is a hidden element which cannot accept the focus. Also, my application has many disabled fields which also cannot accept the focus. The code below doesn't work in all situations: document.forms[0][0].focus();
My next idea was to loop through the items of the first form and find the first non-hidden, non-disabled element. The code below still doesn't fulfill my ultimate requirement because sometimes I have multiple forms on a page: var bFound = false;
for(i=0; i < document.forms[0].length; i++)
{
if (document.forms[0][i].type != "hidden")
{
if (document.forms[0][i].disabled != true)
{
document.forms[0][i].focus();
var bFound = true;
}
}
if (bFound == true)
break;
}
SolutionThe problem with the code above is that it has a hard coded reference to var bFound = false;
// for each form
for (f=0; f < document.forms.length; f++)
{
// for each element in each form
for(i=0; i < document.forms[f].length; i++)
{
// if it's not a hidden element
if (document.forms[f][i].type != "hidden")
{
// and it's not disabled
if (document.forms[f][i].disabled != true)
{
// set the focus to it
document.forms[f][i].focus();
var bFound = true;
}
}
// if found in this element, stop looking
if (bFound == true)
break;
}
// if found in this form, stop looking
if (bFound == true)
break;
}
I copied the code above into a .js file and included a reference on all pages of my application. Now, no matter what inputs are disabled on a form, the focus finds its way to the first one that is enabled.
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||