Thursday, April 16, 2009

Focus the first control of your page

In all pages we have to put the focus on the first control of the page. It can be a textbox,a radio button, a checkbox, a select field, a textarea or a button. For my current project i have created a function which i have placed inside the masterpage and it will traverse through the page starting from a particular control (inside the control) and will take the first occurance of the above types of control and will put the cursor focus on the control. Below is the javascript code i used to achieve this

function selectFirstControl()
{
var objIP = getFocusableControl(document.getElementById('tdContentBody'));
if(objIP!=null)
{
objIP.focus();
return;
}
}

function getFocusableControl(parentCtrl)
{
if(!$(parentCtrl).visible())
return null;
if(parentCtrl.tagName == "INPUT")
{
if(parentCtrl.getAttribute("type")=="hidden")
{
return null;
}
return parentCtrl;
}
else
{
if(parentCtrl.tagName == "SELECT")
{
return parentCtrl;
}
}
var children = $(parentCtrl).childElements();
for(var i = 0;i<children.length;i++)
{
var resCtrl = getFocusableControl(children[i]);
if(resCtrl != null)
return resCtrl;
}
}


Call the function selectFirstControl(); from the bottom of your page.
Here i have called the function "getFocusableControl" recursively to get the control. It is checking the tagname of the node, if it is "Input" or "Select" then it is excluding the hidden fields by checking the type property for for inputs and if it is not hidden, then it is putting the focus on the control.
Iam checking if the parent control visible or not with $(parentCtrl).visible() which is a function from prototypejs to check the visibility. But this checks for the inline "display" property of the element, if "display :none" it returns false. But it cannot check if you are using the hidden property of hiding the control with stylesheet class.
If you are not using prototypejs, you can check the direct style property of the control.

2 comments:

Brandon Grossutti said...

Tarun, I noticed u posted on a site recently having issues with codecs and ffmpeg, did you find a solution?

Mark Farrell said...

Wonderful post.

Castors