Link to home
Start Free TrialLog in
Avatar of Batalf
BatalfFlag for United States of America

asked on

Array in forms

I have a form like this

<form>
<input type="hidden" name="hiddenField" value="">
<input type="text" name="field[0]" value="a">
<input type="text" name="field[1]" value="b">
<input type="text" name="field[2]" value="c">
</form>

With Javascript, is there an other way to refer to "field[0]" than with

document.forms[0].elements[1].value

??

If I have a lot of form-fields in the form, it's hard to keep track of the index of each element.

What I'm thinking of is something similar to

document.forms[0].field[0].value

but which is legal.

Batalf

Avatar of knightEknight
knightEknight
Flag of United States of America image

I would not use [ or ] in your field names, but you can do this:

  <form name='myform'>
   <input type="text" name="field0" value="a">
   <input type="text" name="field1" value="b">
   <input type="text" name="field2" value="c">
  </form>



and then in your script:

  for ( var i=0; i<3; i++ )
  {
     alert( eval("document.myform.field" + i + ".value") );
  }
or:

   for ( var i=0; i<3; i++ )
   {
      alert( eval("document.forms[0].field" + i + ".value") );
   }
Avatar of Batalf

ASKER

But then it's a little bit harder to read by our serverside-script(PHP). It's easier to just loop through an array.

Batalf
then just give all your fields the same name:

 <form name='myform'>
  <input type="text" name="myfield" value="a">
  <input type="text" name="myfield" value="b">
  <input type="text" name="myfield" value="c">
 </form>


  for ( var i=0,n=document.forms[0].myfield.length; i<n; i++ )
  {
     alert(document.forms[0].myfield[i].value);
  }
... the browser will create an array of fields off the form call "myfield", and you can loop thru it as above.
Avatar of Batalf

ASKER

Hm. Interesting idea you present here. I didn't know that Javascript did that. But: The problem with this solution is that PHP on the server doesn't recognize myfield as an array. It looses all values except the last one only the value "c" seems to be sent to the server.

Batalf
well, I am not comfortable using [ or ] in field names, but if it works for you in every other respect, then perhaps a variation on my previous idea will work (not tested)


  <form>
   <input type="hidden" name="hiddenField" value="">
   <input type="text" name="field[0]" value="a">
   <input type="text" name="field[1]" value="b">
   <input type="text" name="field[2]" value="c">
  </form>



  for ( var i=0; i<3; i++ )
  {
     alert( eval("document.forms[0].field[" + i + "].value") );
  }
ASKER CERTIFIED SOLUTION
Avatar of knightEknight
knightEknight
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Batalf

ASKER

Thank you! That did the trick.