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

Keith Levi, Sep 29, 2008 03:41 PM

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

Uriel, Nov 21, 2008 11:46 AM

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

q, May 13, 2009 04:47 AM

thanks!

Richard Muir-Gladman, Oct 2, 2010 02: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 02:52 PM

Well, the code tag is buggy…

That should read

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

Enter your comment
 
front-end-tech/javascript/using-php-input-arrays-with-javascript.txt · Last modified: May 9, 2008 02:35 AM by dordal
© 2005-10 David Ordal / DO IT, LLC. All Rights Reserved.