Last Updated: 20 Oct 2023

   |   

Author: 135.181.114.235

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
front-end-tech:javascript:using-php-input-arrays-with-javascript [May 9, 2008 07:35 AM]
dordal
front-end-tech:javascript:using-php-input-arrays-with-javascript [Oct 20, 2023 08:45 PM]
135.181.114.235 old revision restored (Oct 20, 2023 11:50 AM)
Line 1: Line 1:
 += Using PHP Input Arrays with Javascript =
  
 +PHP allows you to name multiple form elements with the same name (appended by square brackets):
 +
 +<code html>
 +<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>
 +</code>
 +
 +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:
 +<code javascript>
 +document.forms['myForm'].elements.myInput[0]
 +</code>
 +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:
 +<code javascript>
 +document.forms['myForm'].elements['myInput[0]']
 +</code>
 +Since ''myInput[]'' is now being passed in as a string, and not a JS identifier, you're fine.