5,445,109 members and growing! (14,938 online)
Email Password   helpLost your password?
Web Development » Client side scripting » General     Intermediate

Set Focus to First Input on Web Page

By JohnStanfield

Sets focus to the first input that is not disabled and not hidden.
Javascript, Windows, Dev

Posted: 9 Sep 2005
Updated: 9 Sep 2005
Views: 74,728
Bookmarked: 18 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
8 votes for this Article.
Popularity: 3.85 Rating: 4.27 out of 5
2 votes, 25.0%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
2 votes, 25.0%
4
4 votes, 50.0%
5

Introduction

I 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

  1. At each step of the authorization stage, write hard-coded code to set the focus to an input (i.e. duplicate logic dozens of times on dozens of pages).
  2. Write client-side JavaScript to dynamically handle it.

A Few Tries

Since 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;
}

Solution

The problem with the code above is that it has a hard coded reference to forms[0], so it will not work when the input you want to set the focus to is not within the first form. For example, a complex page might contain several forms for various purposes. My final solution was to use a nested loop that loops through all forms until it finds an input that is not hidden and not disabled. The code below has been tested in Internet Explorer 6.0 and Mozilla Firefox 1.0.4:

  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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

JohnStanfield


John Stanfield, MBA, has been an application architect and developer for eight years, currently using C#, VB.Net, Microsoft Visual Studio.NET, and Microsoft Visual Studio 2005.
Occupation: Web Developer
Location: United States United States

Other popular Client side scripting articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 12 of 12 (Total in Forum: 12) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralThere is a ready to use solution for ASP.NET 2.0memberWereWolf0071:55 19 Aug '08  
GeneralImprovedmemberWarazen6:14 19 Mar '08  
QuestionQuestion?memberchimchim4:58 9 Nov '06  
GeneralBetter ImplementationsussJoel P4:57 14 Sep '05  
Generalhidden parent element?memberjcluggish4:33 14 Sep '05  
GeneralNo forms ?memberzefrit10:21 13 Sep '05  
GeneralRe: No forms ?memberJohnStanfield15:10 13 Sep '05  
GeneralYou need one more conditional testmemberDidier Frund7:29 13 Sep '05  
GeneralRe: You need one more conditional testmemberJohnStanfield14:58 13 Sep '05  
GeneralDrawbacksussAnonymous21:05 12 Sep '05  
GeneralRe: DrawbackmemberJohnStanfield14:56 13 Sep '05  
GeneralRe: DrawbackmemberCode Deamon2:31 5 Sep '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Sep 2005
Editor: Smitha Vijayan
Copyright 2005 by JohnStanfield
Everything else Copyright © CodeProject, 1999-2008
Web17 | Advertise on the Code Project