Add/Remove Input Fields Dynamically with jQuery

If you are looking to add and remove duplicate input fields, here’s another jQuery example below to do the task for you. This jQuery snippet adds duplicate input fields dynamically and stops when it reaches maximum.

add-remove-fields

If you read comment lines carefully, the process is pretty straight forward. We start with 1 input field and let user add more fields until the count reaches maximum. Same process goes to delete button, when clicked, it removes current text field by removing the parent element, which is div element.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
   
    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });
   
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

HTML Code

Here’s HTML code you need to place within BODY tag of your page, perhaps within a FORM tag.

1
2
3
4
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>

Demo

We start with single Input field and a “Add more Field” button to allow user to add more fields. The text input field is wrapped in div element, as explained above, on delete button click, it finds parent element, which is a div and removes it.
Capture array values using PHP from these input fields in next post.

171 Comments Add Comment

  • What if you have two input fields . Because i am trying your code and it duplicate the two input instead of one

     Reply
  • Very useful!! Thanks for sharing

     Reply
  • hi what about php file in controler

     Reply
  • when we write add text field or remove text field code, then how would be save data in database according to their requirements.
    Any help would be great thankful.

     Reply
  • How do you then go about grabbing these items with PHP $POST?

     Reply
  • If I Have Four Or Five Field In A Row Then How Data Submit In MySQL . Because Value Can’t insert into data base , it’s inserted same value in data base , check my code wrong or write

    Ajax:-

    $(document).ready(function(){
    var maxField = 10; //Input fields increment limitation
    var addButton = $(‘.add_button’); //Add button selector
    var wrapper = $(‘.field_wrapper’); //Input field wrapper
    var fieldHTML = ‘‘; //New input field html
    var x = 4; //Initial field counter is 1
    $(addButton).click(function(){ //Once add button is clicked
    if(x < maxField){ //Check maximum number of input fields
    x++; //Increment field counter
    $(wrapper).append(fieldHTML); // Add field html
    }
    });
    $(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
    e.preventDefault();
    $(this).parent('div').remove(); //Remove field html
    x–; //Decrement field counter
    });
    });

    Form Field:-

    PHP:-

     Reply
  • Thanks for it.
    but in $(wrapper).append
    I want to add Ajax load with MySQL data then what I have to do.
    code is:
    $(wrapper).append(”

    2
    Select Repairquery($sql) as $row[]) { echo ‘$row[][repairType]’; } ?>
    Select Title price

    Remove
    “);

     Reply
  • Thank you for this js example, it helped me greatly! Cheers!

     Reply
  • Thank you my friend, really help me.

     Reply
  • $ is not define, please fix or add /*global $*/

     Reply
  • modified design for bootstrap user
    HTML Add

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    $(document).ready(function() {
        var max_fields      = 10; //maximum input boxes allowed
        var wrapper         = $("#TxtBoxContainer"); //Fields wrapper
        var add_button      = $("#AddMore"); //Add button ID
       
        var x = 0; //initlal text box count
        $(add_button).click(function(e){ //on add input button click
            e.preventDefault();
             if(x < max_fields){  //max input box allowed
                $(wrapper).append("+"+ // onkeyup="onInputKeyUp(event)"
                '<a href="#" rel="nofollow">&nbsp;&nbsp;x</a>'); //add input box
                x++; //text box increment
            }
        });
       
        $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
            e.preventDefault(); $(this).parent('div').remove(); x--;
        });
    });
     Reply
  • It’s a Super Post.

     Reply
  • Thank you so much

     Reply
  • Thanks for the code it worked well with for the UI part. but im not able to fetch the values from codebehind using c#

     Reply
    • Hi Abhishek,

      Did you find a solution to fetch the data from the dynamical part ?

      I have the same trouble, the fix part of my form work well, but I can’t fetch the “dynamical” datas.

  • Great stuff! Thanks. I’ve modified it a bit so that it can be used more than once in the same form.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
        $(document).ready(function() {

            init_multifield(10, '.input_fields_wrap', '.add_field_button', 'user_music[]');
            init_multifield(10, '.input_fields_wrap2', '.add_field_button2', 'user_music2[]');


            function init_multifield(max, wrap, butt, fname_p) {
                var max_fields = max; //maximum input boxes allowed
                var wrapper = $(wrap); //Fields wrapper
                var add_button = $(butt); //Add button class
                var fname = fname_p;

                var x = 1; //initlal text box count
                $(add_button).click(function (e) { //on add input button click
                    e.preventDefault();
                    if (x < max_fields) { //max input box allowed
                        x++; //text box increment
                        var cstring = '$(wrapper).append(\'<div><input type="text" name=' + fname + '><a href="#" class="remove_field">Remove</a></div>\');' //add input box
                        eval(cstring);
                    }
                });

                $(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
                    e.preventDefault();
                    $(this).parent('div').remove();
                    x--;
                })
            }
        });
     Reply
    • Steve,
      Do you have an example of the HTML portion you are using?
      I have everything setup for a single use but have a need for more than one in a form.
      I am still fairly new to this kind of stuff so I need examples :)

      Thanks,
      Scott

    • Hi

      Nice code …works very fine but the issue comes in when saving the records in the database .Do you have a working copy that you can shed some light on this issue.

      im using mysql as my db and action php

    • Steve,

      Did you have an example of the HTML portion of the following so that it can be used more than once in the same form?

      $(document).ready(function() {

      init_multifield(10, ‘.input_fields_wrap’, ‘.add_field_button’, ‘user_music[]’);
      init_multifield(10, ‘.input_fields_wrap2’, ‘.add_field_button2’, ‘user_music2[]’);

      function init_multifield(max, wrap, butt, fname_p) {
      var max_fields = max; //maximum input boxes allowed
      var wrapper = $(wrap); //Fields wrapper
      var add_button = $(butt); //Add button class
      var fname = fname_p;

      var x = 1; //initlal text box count
      $(add_button).click(function (e) { //on add input button click
      e.preventDefault();
      if (x < max_fields) { //max input box allowed
      x++; //text box increment
      var cstring = '$(wrapper).append(\'Remove\’);’ //add input box
      eval(cstring);
      }
      });

      $(wrapper).on(“click”, “.remove_field”, function (e) { //user click on remove text
      e.preventDefault();
      $(this).parent(‘div’).remove();
      x–;
      })
      }
      });

  • thank you

     Reply
  • Complete newbie here but I can’t even get the code with no edits to work. Feeling pretty silly.

    Script in the head in between tags and and the html in the body between tags?

     Reply
  • Hi , I used the code above and did not change anything. I would like to ask why mine is not working? When i try to click add more fields. it doesn’t show anything. Hoping to get your soonest response.

     Reply
    • Same with me. I put the HTML code in a php file and also inserted the JQuery code within script tags in the same php file. What am I doing wrong? Cos its not working for me.

    • Could it be possible that you use Adblock? I disabled my Adblocker and then it worked fine.

      Hope this helps you,
      Skayo

  • Hello,
    how would you do this if in stead of input boxes you would have dropdown(s)? I mean, on the basic form you only have one dopdown which is populated from a mysql DB. when you click the add_button it would add another dropdown that is (again) populated from DB?

     Reply
    • Hi Erik, this is what i am trying to do with json data. Did you manage to find a solution to this. Its just that i am new to this (4days), and it is driving me insane trying to find a answer to this problem.

  • I have changed my convenience but when I earned my only generates validation to the first input and the other does not

     Reply
  • Thank your code helped me a lot but as could validate the two text fields when no value is input

     Reply
  • Top-tier thanks to you. You made my night effective

     Reply
  • I need a little help from you guys. Suppose I have submitted a form with three input values(using add more fields) and saved it in database. I want to edit the values in another form, How can I display the saved values in three text box?

     Reply
  • Thanks! You saved me a little time in a huge project! :)

     Reply
  • i want to use it as select option in place of input field once i add those field it should save and display the fields how can i do that

     Reply
  • Its good but when i remove a field,all the fields are removed

     Reply
  • It’s a Super Post.

     Reply
  • How can i sign up your newsletter

     Reply
  • how it works on wordpress..?

     Reply
  • Whenever I get to add this feature. I reach your post. Great work man! :)

     Reply
  • I see how to add the fields, but how do you collect all the values when submitting the form. It appears the DOM doesn’t know about the new field elements. I tried grabbing the values by using serialize() and by looping through the wrapper class. Neither method could see the values in the new fields. Any suggestions?

     Reply
  • How I can delete all rows at once?

     Reply
  • hello
    thank you for this post

     Reply
  • Thanks. it si very important for me.

     Reply
  • i have problem in adding nearly 8 field by add more functionality , what can i do?

     Reply
  • very nice tutorial….

    thank you sooooo much

     Reply
  • Great Demonstration!! Helped me a lot!! I went for FineUploader.com but this one is far more easy and controllable.

     Reply
  • Hello! Bravo for the code!!!

    Only a little thing. How I could controller the boxes not empty? I mean,… if the input is not empty the button would be off.

    Excuse me for my english!

     Reply
  • Thnx..:-)
    Great work…

     Reply
  • cool..!
    i’ve use this in my project and have 1 question..when we add more field in form and then submit..can we count the field we have submited??

     Reply
    • Yes. The question is how do you want to count it?
      With PHP: $_POST[‘mytext’] will be an array, thus you can count it like this: count($_POST[‘mytext’]).

  • hello please the remove part is not working . can someone help please

     Reply
  • When I want to get the value from the input fields the first one is fine, but I can’t seem to get the other values

    1
    2
    3
    $(wrapper).append('Remove'); //add input box
    $value1 = $_POST['mytext1'];
    $value2 = $_POST['mytext2'];
     Reply
  • Osi, I think You don’t have .wrapper on your page

     Reply
  • When I add a textbox it makes my background bigger. When removing a textbox it makes it smaller.

     Reply
  • I’ve try your code

    $(document).ready(function() {
    var max_fields = 10; //maximum input boxes allowed
    var wrapper = $(“.input_fields_wrap”); //Fields wrapper
    var add_button = $(“.add_field_button”); //Add button ID

    var x = 1; //initlal text box count

    $(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max input box allowed
    x++; //text box increment
    $(wrapper).append('Remove‘); //add input box
    }
    });

    $(wrapper).on(“click”,”.remove_field”, function(e){ //user click on remove text
    e.preventDefault(); $(this).parent(‘div’).remove(); x–;
    })
    });

    Add More Fields

    but, when I try to click on Remove, it doesn’t work and appear an error “Uncaught TypeError: Object # has no method ‘on'”

    what should I do ???
    thank you

     Reply
    • Same issue as Osi. Remove line is broken, receive “Uncaught TypeError” on load and then it executed the # link.

    • “On” method only works in jQuery 1.7 or later, for previous jQuery version use “bind”.