Last Updated: 20 Oct 2023
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
saves me from hell! great information here!!!!
Thanks! It was hard to find the answer to this in Google :P
thanks!
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]']…
Well, the code tag is buggy…
That should read
var elem = document.forms['myForm'].elements;
… elem['myInput[0]' …