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?

29 Comments

  1. Harold Rau says:

    Hi,

    Your script works fine for adding several fields. Can you assist me in adding additional fieldsets or group of fields to a form that include multiple lines and a dropdown menu?

    Your help would be appreciated.

  2. DaijoubuKun says:

    I would be glad to help, check your e-mail for a message from me and lets see what I can do.

    UPDATE! It looks like we have resolved the issue. I found out that you can’t use my script to add multiple div tags at once. Also it seems you can’t have any div tags inside the main div that is added. Someday I will figure out how to solve that issue, but for now… Well I don’t know what to tell ya. Best of luck!

  3. Steve McClintic says:

    Your script to dynamically add fields works great. After you submit, it takes you to another page that has a link to the page you submitted from. How would you adjust the page so that it would remember that you had dynamically added a few fields when you press the link? (I was hoping that the back button would remember the extra fields that were added.)

  4. DaijoubuKun says:

    I’ve been trying to figure that one out myself, I haven’t had time to write up anything yet, but anything I did you wouldn’t be able to use your browsers back button without some javascript to stop the user from clicking back. Sorry, at this time I do not have a solution for you.

  5. sanjitster says:

    Hey thanks for the tutorial, But I am stuck when it comes to removing the field.. How do i include the remove function in

  6. DaijoubuKun says:

    I never did figure that part out, sorry. If I ever do figure it out I will e-mail you the code.

  7. Bradley says:

    Love this script – so succinct and functional! Brilliant work mate.

  8. Curtis says:

    Thx for the code. I’ve used it and its great. However I can’t get my data our of the $_POST global. Its in $_GET. I have the form set to method=”POST” but it appears using a div and replicating it breaks $_POST. Am I doing something wrong or just missing something?

    Thx.

    Curtis

  9. inac says:

    nice tutorial.
    Please i want 5 fieds to show at first when i open the form
    before clicking on add field button to add other fields. Please help.

    Thanks.

  10. DaijoubuKun says:

    That can be done. First in your HTML put something like (using blog post example):

    <div id="phone">
    	Name<input type="text" name="phone_0" value="" />
    	Number<input type="text" name="phone_num_0" value="" /><br>
    	Name<input type="text" name="phone_1" value="" />
    	Number<input type="text" name="phone_num_1" value="" /><br>
    	Name<input type="text" name="phone_2" value="" />
    	Number<input type="text" name="phone_num_2" value="" /><br>
    	Name<input type="text" name="phone_3" value="" />
    	Number<input type="text" name="phone_num_3" value="" /><br>
    	Name<input type="text" name="phone_4" value="" />
    	Number<input type="text" name="phone_num_4" value="" /><br>
    </div>
    <div id="add_phone" style="display: none;">
    	Name<input type="text" name="phone_" value="" />
    	Number<input type="text" name="phone_num_" value="" /><br>
    </div>

    then in your JS change the line from:

    var phone_counter = 0;

    to:

    var phone_counter = 4;

    This will start your count at 5.

    Sorry, I would have just reposted the origional JS code, but for some reason all my ‘< ' and '>‘ syntaxes kept getting changed to HTML Tags. Oh well. I think you get the idea.

  11. Nathan says:

    Is it possible to also increment the id field? i had a stab at it with no luck.

    Cheers Nath

  12. sch says:

    Could you please advise how I can dynamically add a form inside which I’m also able to add dyncamic fields. For e.g: I want to collect info of Members. i don’t know in advance how many people. i want to have a button say: ‘add more member’. In side a member form i also want to collect info of his/her children, so i need to have a button say: ‘add more kid’. Something looks like:
    —–
    Member #1:
    Name:…
    Kid#1….
    Button(Add more kid)
    Button(Add more member)
    ——

    I’ve tried do something similar:
    —–

    ..what displayed as default..

    ….

    ..what displayed as default..

    ….

    ——

    I was able to generate new Member form let say Member# 2, 3, 4….But my problem is that when I click the button ‘add more kid’ in side the new generated Member# 2,3,4… form the new fields are always generated in the Member#1 form. The document.getElementById(add_child) always refers to the first div not cloned one for the Member# 2,3,4…..

    Could you please guide me to solve the problem.

    Thanks for your help.
    sch.

  13. DaijoubuKun says:

    Add this code inside the var for statement just before the close bracket. It’s not the best solution, but it should work.

    var theName = newField[i].id
    if (theName)
         newField[i].id = theName + counter;
  14. sch says:

    Many thanks DaijoubuKun. However I still can’t get it work. Could you tell me how I can post my code here so you can see what is wrong.

    Let me try to put my code here:

    `

    "

    var counter = 0;

    function add_child() {
    counter++;
    var newFields = document.getElementById('add_child').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('child');
    insertHere.parentNode.insertBefore(newFields,insertHere);

    }

    var compter = 0;

    function add_member() {
    compter++;

    var newFields = document.getElementById('add_member').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 + compter;

    }
    var insertHere = document.getElementById('add_member');
    insertHere.parentNode.insertBefore(newFields,insertHere);
    }

    Member:

    Member:

    "

    `

  15. Maxcim says:

    Hi,

    first of all thank you for the script. I was looking for this.

    I have only one question:
    Why does this work:

    Naam:
    Geboorteplaats:
    Geboortedatum:

    Naam:
    Geboorteplaats:
    Geboortedatum:

    But this doesn’t:

    Naam:
    Geboorteplaats:
    Geboortedatum:

    Naam:
    Geboorteplaats:
    Geboortedatum:

    If i put the form in a table, only the data from the first div is send but not the data from the second div, .

    Thank you :D

  16. jim says:

    hi, am really new in javascript but i wanted to post this one as it worked when i tried it.. it removed the newly added field.

    just add this code:

    in the div with id “add_phone”

  17. Kazi says:

    Hi there,

    I really found your code useful for my own purpose. However would you be able to provide the “Remove” script to delete the fieldsets created?? thanks.

  18. DaijoubuKun says:

    At this time I have found the code I have on this post has issues when you try to remove. A friend of mine says he has a version where you can remove. He hasn’t given it to me yet as there are a few kinks (as in it doesn’t work with some web browsers) As soon as I have a good working version I will modify this post to inform everyone, and write up a new post explaining how it works.

  19. Cameron Graeter says:

    No joke you know what you are talking about , thank you

  20. thanks for this tutorial …
    Is there a script for “remove” this field which “add” before ?!?

  21. DaijoubuKun says:

    As previously noted I DO NOT have a remove field script. A friend tells me he has one, he has yet to provide me the code as there are some issues he would like to resolve. As soon as I have it I will post it.

  22. Alexis says:

    Hi,

    This is really useful, thanks!

    One question, how would I go about automatically setting the focus to the most recently added field?

  23. DaijoubuKun says:

    That is a great question. The answer is… I don’t know. I will have to look into that. Please check back and hopefully I will have found an answer for you.

    EDIT: I love google. Try this out: http://www.codeave.com/javascript/code.asp?u_log=7017

  24. Alexis says:

    Thanks for the quick reply! I’m having trouble getting it to work. I made a form to use with a barcode scanner to scan in multiple barcodes to post to my database. The scanner adds a tab after the barcode, but instead of the focus jumping to the newly added field it jumps to the Add Row button. Any help is much appreciated!

    // JavaScript Document
    //http://www.tangorangers.com/examples/dynadddynpost/index.php
    var counter = 0;
    //Start a counter. Yes, at 0
    function add_barcode() {
    counter++;
    // I find it easier to start the incrementing of the counter here.
    var newFields = document.getElementById(‘add_barcode’).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_barcode');
    // Inside the getElementById brackets is the name of the div class you will use.
    insertHere.parentNode.insertBefore(newFields,insertHere);
    document.form_addMediaLogEntry.name[theName].focus();
    }

    <form action="” method=”post” enctype=”multipart/form-data” name=”form_addMediaLogEntry” id=”form_addMediaLogEntry”>

    Barcodes:

  25. DaijoubuKun says:

    I have tested the code over and over again. I can not see why when your scanner would send the Tab that it wouldn’t goto the next field. I tested this under IE8 and FireFox in XP and FireFox on Linux. Every time I manually hit the Tab button it moves to the next field. Did you have this problem before adding the javascript? Have you tried just typing in some numbers and hitting Tab to see how it reacts? Perhaps the scanner isn’t sending the correct key.

  26. Alexis says:

    Yes, I tried manually keying in numbers and hitting tab and it does the same thing in Firefox and IE – skips the new field and goes to the button. Just realized that the code for the form got left out of my post above. Again, I really appreciate your help with this!

    <form action="” method=”post” enctype=”multipart/form-data” name=”form_addMediaLogEntry” id=”form_addMediaLogEntry”>

    Barcodes:

  27. Alexis says:

    maybe if I escape the double and single quotes…
    <form action=\"\” method=\”post\” enctype=\”multipart/form-data\” name=\”form_addMediaLogEntry\” id=\”form_addMediaLogEntry\”>

    Barcodes:

  28. Alexis says:

    Fixed it! I had the add_barcode() function called by an onChange event in the text fields. Setting it to onFocus fixed it. Thanks for the code and your help!

  29. jcode says:

    Hey I was wondering if you could help me out. I am creating a form where people can add more crates to their order by clicking the “add” button. When they click it, I would like it to return my unique_input field. Any thoughts?

    Crate

    Next Crate (Width x Height x Depth):

    function add(type) {

    //Create an input type dynamically.
    var element = document.createElement("input");

    //Assign different attributes to the element.
    element.setAttribute("type", type);
    element.setAttribute("value", type);
    element.setAttribute("name", type);

    var foo = document.getElementById("unique_input");

    //Append the element in page (in span).
    foo.appendChild(element);

    }

Leave a Reply