Back to example page

Dynamically add form fields using javascript and DOM with dynamic post method

This is in responce to my blog post here

In this example I will be showing you how to not only use some javascript with DOM support (that way it works on FireFox, IE and possibly more) to add more form input fields but also how to parse that data after the submit button is clicked so that it can be added into the database.
To start I use MySQL for the database so all of my example here will be using it. I'm going to assume you know how to create a database and be able to access it so I'm only going to go over the fields I will be using.

Lets start with the DB table. Lets call it 'phone' for storing a name and phone number.
Database Table
idx int(10), Auto increment, Primary Key
name varchar(30)
numb varchar(20)
Now that we have the db layout lets start the form lets look at the javascript code we need. Now I prefer to use my javascript functions in a separate file. So in between the HTML HEAD tags we put
<script type="text/javascript" src="./functions.js"></script>
Because we need to use Div tags to add new fields we can't use '<div id="add_phone">'. It's against the rules to add multiple Divs that use the 'id' function. We need to use class. That means we must add a little bit extra code. Now as of writing this I'm no expert in javascript. Actually I wouldn't even call myself a beginner, I don't have that much experience. I just do a lot of digging, change things around so they work for me and do these write ups that I hope will help out others.

Add the code to 'functions.js'
If you hit the Hide/Show button below it it will add information to the script to let you know how it works and what you may need to change to get it to work for you.
var counter = 0;
function add_phone() {
    var newFields = document.getElementById('add_phone').cloneNode(true);
    newFields.id = '';
    newFields.style.display = 'block';
    var newField = newFields.childNodes;
    for (var i=0;i<newField.length;i++) {
        var theName = newField[i].name
        if (theName)
                newField[i].name = theName + counter;
        var insertHere = document.getElementById('add_phone');

Now lets built the form.
<form name="add_a_phone" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<div id="phone">
    <input type="text" name="phone_0" value="" />
    <input type="text" name="phone_num_0" value="" /><br>
<div id="add_phone" style="display: none;">
    <input type="text" name="phone_" value="" />
    <input type="text" name="phone_num_" value="" /><br>
<input type="button" id="add_phone()" onclick="add_phone()" value="Give me more fields!" /><br>
<input type="submit" name="submit" value="submit" />
Notice how in the input button field that the 'id' and 'onclick' are the same. That's important, and yes you do need the brackets for some reason.
Also note that the form name can NOT be the same as any div id!!! I keep making that mistake.
You will need some way of checking how many fields were added when you get to your 'if(isset($_POST['submit'))' statement. This gets a little messy.
Because I like my forms to go back to this page and check if submit was clicked we need to put some php code at the very top.
        echo "You clicked submit!<br>";
        echo "Here is your data<br>";
        echo "<br>";
        if ($_POST['phone_num_0'])
                $continue = FALSE;
                $i = 0;
                while ($continue == FALSE)
                    if (isset($_POST['phone_'.$i]))
                    echo $_POST['phone_'.$i] . " = " . $_POST['phone_num_'.$i] . "<br>";
                    $phone = $_POST['phone_'.$i];
                    $phone_num = $_POST['phone_num_'.$i];
                    $query = "INSERT INTO phone (idx, name, numb) VALUES ('NULL', '$phone', '$phone_num')";
                    $result = mysql_query($query);
                    $continue = TRUE;

Obviously I left out some information. Like connecting to your DB. I'm assuming you already know how to do that.

Now for the example! You can add as many fields as you like and input the data as you feel. Click the Submit button at the bottom and this page will refresh with your added data.

One thing you won't see however (unless you have the web development plug-in for FireFox) is that each time you add a new field the number in the input name increments! So it starts at 0, you click once it adds the field and puts a 1, 2, 3 and so on. Now I did put a limit on this page, you can't add more than 4 lines!
Name Number