Caffeinated
Caffeinated

Reputation: 12484

JavaScript handling of forms, how does this array notation work?

In the following code, this line is a bit strange to me:

var x=document.forms["myForm"]["fname"].value;

The web page:

<html>
<head>
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}
</script>
</head>

<body>

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">

First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>

</html>

How does that work? Where is the multidimensional array ? thanks

Upvotes: 2

Views: 179

Answers (2)

maerics
maerics

Reputation: 156662

The document.forms object is special because it has an interface to identify all the forms in the document by looking up a property as the numerical index (zero based) or by the "name" attribute.

Also, the form object has a similar feature that lets you lookup input elements (and other form widgets) by their name as a property.

Upvotes: 1

Pointy
Pointy

Reputation: 414086

This:

var x=document.forms["myForm"]["fname"].value;

is exactly the same as:

var x = document.forms.myForm.fname.value;

In fact there's really no reason (in this case) for it to be written the way it is.

Now, if instead of those two string constants — "myForm" and "fname" — there were some dynamic mechanism that computed or fetched the names, then the first form makes sense. The [ ] operator allows for an expression to be evaluated to determine a property name to access.

There are no arrays involved in this example at all, by the way. Just object property references.

Upvotes: 1

Related Questions