PDA

View Full Version : Referencing Form Elements


w0lf42
05-24-2004, 09:48 PM
I am aware of the four different ways to access form fields:

<form name="formName">
<input type="text" name="elementName" />
</form>

// create variables
var nameOfForm = "formName"; var nameOfElement = "elementName";

// list form access options
document.forms[0].elements[0].value;
document.forms[nameOfForm].elements[nameOfElement].value;
document.forms['formName'].elements['elementName'].value;
document.formName.elementName.value;

I realize the importance of having all four. My question is, being that the last two options are VERY similar, is there any reason to code with one over the other (i.e. forms['formName'] vs. formName)?

Thanks

n8thegreat
05-25-2004, 12:01 AM
if you had a series of elements that had some sort of numerical increment, such as input1, input2, input3, etc, then you could use the elements['sdf'] to go through each one with a for loop and do something with it.

Jon Hanlon
05-25-2004, 07:05 PM
Personally I use:
document.forms.formName.elementName.value;

You can omit the .forms bit as .forms is the default object collection for the document, but it speeds things up and adds to the readability.

As n8 points out, use the ['whatever'] form when you want to dynamically construct the 'whatever' string (like your 2nd example).