2

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thank you so much Maerics! I am studying the Mozilla references now, very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.