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:
Using PHP it’s easy to iterate through those values now:
// 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:
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.
My name is Alexander Kleshchevnikov. I have been working as a professinal web application developer since 2002. I believe in simple intelligence from server technologies to front-end development. Now I run my own web development consulting company in Ukraine. You can find
Wooow!!! :)