Dynamically add fields to forms
On my old site I had an example of adding fields to forms dynamically, which continued to get hits even long after I had forgotten it was there. The example looked like this:
City
Address1
ZIP
Phone Number
Name
The code looked like this:
[cc lines=”20″ lang=”html”]
function forminsertrow(theForm) {
var insertHere = document.getElementById(\’cloneme\’);
var newElement = document.getElementById(\’cloneme\’).cloneNode(true);
insertHere.parentNode.insertBefore(newElement, insertHere);
}
Search For:
City
Address1
ZIP
Phone Number
Name
[/cc]
This leaves you with kind of an ugly array that looks something like this:
[cc lang=”php”]
$_REQUEST[‘search’][0][‘field’] = ‘address:city’;
$_REQUEST[‘search’][0][‘value’] = ‘Phoenix’;
$_REQUEST[‘search’][1][‘field’] = ‘name:full’;
$_REQUEST[‘search’][1][‘value’] = ‘David’;
[/cc]
You generally need to do something with this to make it more usable. A loop like this one transforms it into a more nicely formatted array:
[cc lang=’php’]
foreach($_REQUEST[‘search’] as $key => $value){
$search[$value[‘field’]] = $value[‘value’];
}
[/cc]
I have used this approach quite successfully, and visitors seem to find it easy to work with. If I was doing this now, I would probably use a javascript library to do the clone part. For example, with jQuery, you don’t need the function at all. Just change the onclick on the button to this:
[cc lang=’javascript’]onclick=’$(“#cloneme”).clone().appendTo(“#cloneme”);'[/cc]
In fact, that’s what the working example above actually does.