Note: There is a newer post that repeats the same functionality of this example but makes use of Knockout.js - Adding Form Fields Dynamically with Knockout.js

Sometimes, for example with a content management system, the user needs the ability to add fields dynamically to a HTML form. As jQuery is the King of DOM then this is an easy task for it to implement.

In this example, we'll use jQuery to create a new node that contains the new form element (in this case a simple textfield) and then add it to DOM.

To make it even more interactive we'll give the user the ability to remove form fields so that they can customise the form to their requirements.

View The Demo

The HTML is just the shell of a form.

<form method="post">
<p>
<span id="addVar">Add Variable</span>
</p>
<p>
<input type="submit" value="Check">
</p>

</form>

When clicking the HTML marked up a as <span id="addVar">Add Variable</span> we want the following HTML added to create a new paragraph that contains a label and textfield.

<p>
<label for="var2">Variable 2: </label>
<input type="text" name="var2" id="var2"><span class="removeVar">Remove Variable</span>
</p>

We'll do this by creating a variable containing the HTML and adding it to the DOM. The HTML contains the seeds of its own destruction. The removeVar class can be used to remove the element.

In this example there is also a block of similar logic to initially add three textfields to the form - although this is not required.

Time for that jQuery magic.

//create three initial fields
var startingNo = 3;
var $node = "";
for(varCount=0;varCount<=startingNo;varCount++){
    var displayCount = varCount+1;
    $node += '<p><label for="var'+displayCount+'">Variable '+displayCount+': </label><input type="text" name="var'+displayCount+'" id="var'+displayCount+'"><span class="removeVar">Remove Variable</span></p>';
}
//add them to the DOM
$('form').prepend($node);
//remove a textfield
$('form').on('click', '.removeVar', function(){
   $(this).parent().remove();

});
//add a new node
$('#addVar').on('click', function(){
varCount++;
$node = '<p><label for="var'+varCount+'">Variable '+varCount+': </label><input type="text" name="var'+varCount+'" id="var'+varCount+'"><span class="removeVar">Remove Variable</span></p>';
$(this).parent().before($node);
});

The jQuery prepend() method is used to add the initial fields and the jQuery before() method adds a new field when the user clicks addVar in the HTML.

18 Thoughts to “Adding Form Fields Dynamically with jQuery”

  1. Nicolas

    I this article http://www.mustbebuilt.co.uk/2012/07/27/adding-form-fields-dynamically-with-jquery/
    the example breaks when removing inputs from the middle and the adding new ones.

    1. admin

      Hi Nicolas

      Thanks for letting me know. I have changed that now so the new fields are always numbered upwards. Hope that works for you now.

      Martin

      1. Robin

        Are you sure you updated this? I'm not seeing it..

        Anyway it's an easy fix as I'm sure you know:

        $('form').on('click', '.removeVar', function(){
        $(this).parent().remove();
        varCount--;

        });

        Btw, thanks for the example!

        1. admin

          To be honest reducing the varCount variable was in the original version and that was what seemed to be what caused it problems (see original). Open to suggestions if there is a neater solution.

  2. Great tutorial. help me a lot

  3. Its really nice tutorial. This makes a form more user friendly. I also created something similar here http://www.infotuts.com/dynamically-add-input-fields-to-form-jquery/. Then I came across lot of queries on how to submit the entered data into database and I found a simple solution here. http://www.infotuts.com/dynamically-add-input-fields-submit-to-database/

  4. Triel

    This is a good tutorial but can you tell me how I would include in the JQuery reading from a text file to populate the ListBox I made for this? (I changed the textbox to a listbox and it works great but I need to read a file such as title.txt and populate the key and text fields with it.)

    File such as:
    | Select Title
    0|Not Assigned
    1|Chief of Police
    2|Accountant
    3|Clerk

    1. admin

      I guess for this I would use JSON. I have posted an amended version that creates a drop-down dynamically here.

      This loads a JSON file using jQuery's $getJSON. The JSON file I formatted as an array and you can see it here.

      Then the logic is pretty similar to the original but obviously it adds <option> elements.

      Hope that helps.

  5. Triel

    Thanks so much for deleting my question and not answering it.

    1. admin

      Erm. I have just replied to this.

      1. Triel

        Sorry, I spoke too soon. I didn't realize you had to approve the comment before it showed up.

        Thank you so very much for your help. I didn't do it exactly like you said because I was unsure how to do the JSON but I got it to work with your help. I really owe you for helping me get through this!!!

        I got my whole program working now EXCEPT for if the person is updating the record. I am not sure how to put in this JQUERY to set the selected option. I have been searching and searching but can't seem to find anything.

        If you could do me one more favor and explain how to put the selected value in I would greatly appreciate it. I populate the page with how many list boxes I need from a hidden field and then I have the values in other hidden fields. The names of them are like hidden1, hidden 2 etc depending on how many fields I needed.

  6. hi, i would like to know how to make this work with jquery-1.9.1

  7. Arun ceramic

    i just want to save those dynamic field values separately using jquery ajax any idea about it

  8. Barry

    This doesn't seem to work with firefox!

  9. Mike

    Hello

    I am wondering if this can then be put dynamically in to a PHP email script?

    I want to create a PHP email form that has
    Bulletin 1 and users can add new lines for more bulletin notes. That is then all emailed under a heading bulletin.

    I can make the email form no problem but how can I get it to dynamically add a line for each field added.

    Thank you

    1. admin

      Not quite sure if this will help but you could try added the values names as an array ie <input type="text" name="myVar[1]">
      I built a version here which uses this technique and also sent it through to a basic PHP script so you can see how the values can be retrieved using PHP's foreach loop.

  10. […] couple of years ago I did a post entitled Adding Form Fields Dynamically with jQuery.  In this post I am going to re-visit the same problem but this time use Knockout.js to create the […]

Leave a Comment