Last Updated: 20 Oct 2023

   |   

Author: 135.181.114.235

Using PHP Input Arrays with Javascript

PHP allows you to name multiple form elements with the same name (appended by square brackets):

<form name='myForm'>
<input type='text' name='myInput[0]' id='myInput[0]' />
<input type='text' name='myInput[1]' id='myInput[1]' />
<input type='text' name='myInput[2]' id='myInput[2]' />
</form>

When you submit this, the $_REQUEST['myInput'] variable becomes an array with all the values from your input boxes. But how do you access these input boxes in Javascript? You can't do:

document.forms['myForm'].elements.myInput[0]

because the square brackets are illegal in an identifier in Javascript, even though they are legal in HTML. (In fact, that would try to access the 0th element of the myInput array, which doesn't exist.) Instead, you can use the array notation for accessing a property of an object:

document.forms['myForm'].elements['myInput[0]']

Since myInput[] is now being passed in as a string, and not a JS identifier, you're fine.

Discussion

203.177.74.135, Sep 29, 2008 08:41 PM

saves me from hell! great information here!!!!

201.152.39.88, Nov 21, 2008 05:46 PM

Thanks! It was hard to find the answer to this in Google :P

217.70.85.68, May 13, 2009 09:47 AM

thanks!

Richard Muir-Gladman, Oct 2, 2010 07:50 PM

If you are accessing more than one control in a function, you can get a significant performance boost by using the following code. The more form elements you need to access, the better the boost.

var elem = document.forms['myForm'].elements; …elem['myInput[0]']…

Richard Muir-Gladman, Oct 2, 2010 07:52 PM

Well, the code tag is buggy…

That should read

var elem = document.forms['myForm'].elements;
… elem['myInput[0]' …

Enter your comment. Wiki syntax is allowed: