[thelist] JavaScript focus & getElementByID

.jeff jeff at members.evolt.org
Thu Jan 16 03:42:01 CST 2003


martyn,

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> From: Martyn Haigh
>
> Could you explain what is wrong with using this
> approach to access form elements?
>
> How would you do it so that it was cross browser?
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

simple, via the forms and elements collections in tandem with name
attributes (which are required for elements already).  these were
implemented in javascript 1.0 so are available in all browsers that support
javascript.

in simple terms, whenever a page is loaded, the browser looks for forms.  it
creates a forms collection accessible via document.forms.  you can access
any of the forms by using array notation (to create an object reference to
the first form in the document):

oForm = document.forms[0];

or, if the form has a name attribute, using associative array notation
(assuming the name attribute value is foo) using either of the following:

oForm = document.forms['foo'];
oForm = document.forms.foo;

now, for each form it finds in the document, it'll create an elements
collection as an object property of the form object the elements belong to.
let's say, for example, your second form on the page has a name attribute
value of login and is made up of three form fields with the following name
attribute values -- username, password, login.  you could access the
password field's value using any of the following (plus a few ridiculous
combinations i didn't include, but you could easily extrapolate from what is
listed below):

document.forms[1].elements['password'].value;
document.forms['login'].elements['password'].value;
document.forms.login.elements['password'].value;
document.forms[1].elements.password.value;
document.forms['login'].elements.password.value;
document.forms.login.elements.password.value;

or, even just the following (provided there are no other objects with a name
attribute value of "login":

document.login.password.value;

my personal preference (for quick recognition) is:

document.forms['login'].elements['password'].value;

i'd rather be verbose and make it very apparent what i'm doing.

does this make things clearer for you?

.jeff

http://evolt.org/
jeff at members.evolt.org
http://members.evolt.org/jeff/




More information about the thelist mailing list