Home page
 
 Home 
 ASP 
 PHP 
 SQL 
 HTML 
 JavaScript 
 Search 
 Contact 
 
Search
or browse popular tags
Subscription

Sign up for the free email newsletter for new tips, tutorials and more. Enter your email address below, and then click the button.

Privacy Policy

RSS Twitter

Set Focus to First Available Form Control

Print

Sometimes it is necessary to set the focus to the first available form control. The problem is that complex web pages can contain multiple forms and each form individually can contain hidden or disabled elements and controls that cannot accept focus.

The code below iterates through all forms skipping hidden and disabled elements and stops when it finds the first available form control:

function SetToFirstControl()
{
  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) 
        {
          try {
             //set the focus to it
             document.forms[f][i].focus();
             var bFound = true;
          }
          catch(er) {
          }
        }
      }
      //if found in this element, stop looking
      if (bFound == true)
        break;
    }
    //if found in this form, stop looking
    if (bFound == true)
      break;
  }
}



Tags:

Add To: Add to dzone dzone | Digg this digg | Add to del.icio.us del.icio.us | Stumble it stumbleupon

  • Comments





Copyright © 2005-2014             www.WebCheatSheet.com All Rights Reserved.