Home > javascript > Dynamically add fields to forms

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:

Phone Number

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:

Phone Number


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’;
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’];
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.

Categories: javascript
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: