faqts : Computers : Programming : Languages : JavaScript : Forms

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

15 of 18 people (83%) answered Yes
Recently 7 of 10 people (70%) answered Yes


How can I index form elements with a name like "field-name"?

Feb 14th, 2001 13:06
Paulo Eduardo Neves, Jeff Pfaff,

Usually if you have a form like this:
  <FORM NAME="formName">
  <INPUT NAME="fieldName" ...>
  <INPUT NAME="anotherFieldName" ...>
you can reference the form elements using: 
However you may have a form with field names containing characters 
which are not allowed in identifiers in JavaScript, such as:
  <INPUT NAME="anotherField-Name" ...>
Using  'document.formName.anotherField-Name' to reference this element 
will cause an error because javascript will view it as a minus sign. 
An easy work around for this is to reference the elements this way 
where x is the number of each 'input' statement in your form.
using this method, you can safely reference the following form 
  <FORM NAME="formName">
  <INPUT NAME="field-Name" ...>
  <INPUT NAME="anotherField-Name" ...>
With these statements
document.formName.elements[0]       (for field-Name)
document.formName.elements[1]       (for anotherField-Name)
Notice that the numbering starts with zero!
You can also access the array notation, it will probably make your code