Using arrays in form element names July 27, 2009

Sometimes there is variable number of similar elements on a form. For example, phone numbers. To iterate all filled values on the server it will be nice to use arrays. And form element naming allow it:

<form method="post">
<input type="text" name="phone[0]" />
<input type="text" name="phone[1]" />

</form>

Using PHP it’s easy to iterate through those values now:

foreach ($_POST[‘phone’] as phone) {
// do something with phone, save in the database
}

But how to access those values with JavaScript? In case we need to validate required fields, for example. It’s easy to suppose that document.forms[0].phone[0].value returns value. Actually no. In this case we need to use document.forms[0].elements array and access by key:

alert(document.forms[0].elements["phone[0]"].value);

Using arrays in form element naming allows us to control the variable number of form elements. For example, we can add link “Add another phone” and when user clicks on it add new <input type=”text” name=”phone[2]” /> field. And we do not need to change anything in PHP code because it will iterate all values that we have passed to the server.

 
One Comments
Oleg August 9th, 2009

Wooow!!! :)

 
Leave a Reply