Archive for May 2009

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

Lets say you need to add some extra text fields but you don’t want to write a bunch of code. I not only have how to quickly and easily add the input fields, but also how to take the data and put in into a MySQL DB!

I start with creating the DB. Lets call the table ‘phone’. We need 3 rows. ‘idx’ int(10) with Auto Increment and primary key. ‘name’ varchar(30), and ‘numb’ varchar(20). You can setup the db how ever you choose. I create the idx so that I have a key field.

Now we need some javascript.

var counter = 0;
Start a counter. Yes, at 0
function add_phone() {
    counter++;
// I find it easier to start the incrementing of the counter here.
    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;
// This will change the 'name' field by adding an auto incrementing number at the end. This is important.
        }
        var insertHere = document.getElementById('add_phone');
// Inside the getElementById brackets is the name of the div class you will use.
        insertHere.parentNode.insertBefore(newFields,insertHere);
}

Now I like to put that in a seperate .js file, but you can add it to your HTML HEAD tag.

Next we need to build the form.

<form name="add_a_phone" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<fieldset>
<div id="phone">
    <input type="text" name="phone_0" value="" />
    <input type="text" name="phone_num_0" value="" /><br>
</div>
<div id="add_phone" style="display: none;">
    <input type="text" name="phone_" value="" />
    <input type="text" name="phone_num_" value="" /><br>
</div>
<input type="button" id="add_phone()" onclick="add_phone()" value="Give me more fields!" /><br>
<input type="submit" name="submit" value="submit" />
</fieldset>
</form>

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.

<?php
    if(isset($_POST['submit']))
    {
        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);
                }
                else
                {
                    $continue = TRUE;
                }
                $i++;
            }
        }
    }
?>

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

I first wrote this on my main page. This post is almost a copy/paste from the main page. I like adding it to the blog since it gets better indexing from search engines and hopefully the information will be useful to you. On the main page there is also a working example so you can see how it all ties in. Check it out Here

Questions?