[Javascript] Selecting a form element

Jonathan Buchanan jonathan.buchanan at gmail.com
Wed Oct 4 10:08:50 CDT 2006


> If I have a form element like
>
> <input type="text" name="mydata">
>
> Is there a way to select it in a similar manner to getElemntById()? I
> know how to do something like "document.forms.FORMNAME.mydata" but
> that requires me to know the name of the surrounding form which may
> not be named. I also know that I could add an id and use the
> ubiquitous getElementById(), but I would like to be able to select it
> just by its name.
>
> Any Ideas?
>
>
> Terry

Is there any reason why you're not willing to give it an id?

You could access the containing form by index, e.g. the following if
the containing form is the first form on the page:
document.forms[0].elements["mydata"]

Alternatively:
function getInputByName(name)
{
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++)
    {
        if (input[i].name == name)
        {
            return input[i];
        }
    }
    return null;
}

Jonathan.



More information about the Javascript mailing list