Entry
How can I index form elements with a name like "field-name"?
How can I index form element names consisting of a prefix plus a changing number?
Mar 11th, 2000 03:37
Martin Honnen,
Usually if you have
<FORM NAME="formName">
<INPUT NAME="fieldName" ...>
you can reference that form element as
document.formName.fieldName
You might however have form field names containing characters which are
not allowed in identifiers in JavaScript e.g.
<INPUT NAME="field-name" ...>
Then using
document.formName.field-name
will through an error as the - is interpreted as the minus symbol.
Fortunately JavaScript knows the bracket notation as well for
properties so
document.formName['field-name']
rescues you.
The same bracket notation is helpful if you have a couple of fields
with the same name prefix but a running numerical index e.g.
<INPUT NAME="field1" ...>
<INPUT NAME="field2" ...>
...
<INPUT NAME="field10" ...>
and want to process all fields with the same code. You write a loop
for (var i = 1; i <= 10; i++) {
var field = document.formName['field' + i];
// process/check/ field here
}
which indexes the document.formName object as needed.