Tuesday, August 30, 2005

Set Focus to First Input Element

Here's a nifty little javascript function I wrote to set the focus to the first input element within an HTML document, or within the specified element in the HTML document.

function setFocus(el)
{
    if (!el)
        el = document.documentElement;
    var children = el.childNodes;
    var i = 0;
    for (i = 0; i < children.length; i++)
    {
        if (setFocus(children[i]))
            return true;
    }
    if (el.tagName == "INPUT" ||
        el.tagName == "SELECT" ||
        el.tagName == "TEXTAREA")
    {
        if (el.tagName == "TEXTAREA") {
            if (el.readOnly == false && el.disabled == false)
                el.focus();
        }
        else {
            if (el.disabled == false)
                el.focus();
        }
        return true;
    }
    return false;
}

No comments: