Add/remove form elements using jQuery

May 31, 2007

This is a simple tutorial about creating and removing HTML form elements dynamically using jQuery without any page refresh. It is exactly like the one found in Gmail compose mail page at the file attachment area. I actually needed this functionality for a little project I’m currently working on. I managed to find a few good tutorials about this subject on the net, most notable was Dustin Diaz’s technique using purely hand-written javascript (without any JS framework). However, with the availability of many good and stable JS frameworks these days, I decided to give it a try using jQuery.

The code to add and remove elements from the page is very short and simple. The only thing that will make it long is ‘how huge is your form gonna be?’. That is, ‘how many HTML form elements do you want to add at one time?’.

Before we get started, you might want to check out the demo. This script has been tested in Firefox 1.5, Firefox 2.0, IE6 and IE7.

First of all, you will need these files to begin:

1. OK, first I’m gonna import both JS in the <head> of my html doc.

<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery.highlightFade.js"></script>

2. Then, create a form with a <div> nested inside it. Also create an <a> tag that will be used to generate the form. The <input type=”hidden”> is required in order to ensure a unique id is assigned to every newly generated form elements.

<p><a href="#" onClick="addFormField(); return false;">Add</a></p>
<form action="#" method="get" id="form1">
<input type="hidden" id="id" value="1">
<div id="divTxt"></div>
<p><input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset"></p>
</form>

3. Next, the JS code for adding the form. The form element being added is wrapped inside a <p> with an id corresponding each row. The simple jQuery function used here is $().append(). At the same time, we also create a ‘remove’ anchor right next to the elements we added. These anchor will be used to invoke the function to remove the particular row. Next, a nice little highlight effect is added to the <p> using highlightFade jQuery plugin and finally the value of <input type=”hidden” id=”id”> is incremented.

function addFormField() {
var id = document.getElementById("id").value;
$("#divTxt").append("<p id='row" + id + "'><label for='txt" + id + "'>Field " + id + " <input type='text' size='20' name='txt[]' id='txt" + id + "'> <a href='#' onClick='removeFormField(\"#row" + id + "\"); return false;'>Remove</a><p>");

$(‘#row’ + id).highlightFade({
speed:1000
});

id = (id – 1) + 2;
document.getElementById(“id”).value = id;
}

4. Finally, the JS code for removing form elements. Basically, what this function does is remove the <p> that wrapped the form elements, using jQuery function $().remove(). As a result, everything will be removed safely (not hidden) from the form. This can be seen when you submit the form; only values from the visible text fields are sent to the browser.

function removeFormField(id) {
$(id).remove();
}

Click here to view the demo.

118 Responses to “Add/remove form elements using jQuery”

  1. oldmateluke Says:

    Hey dude thanks heaps for this it’s great! I’m only new to this stuff, and I have run into a bit of a problem. I have this as the form controls being added, which inserts great,

    $(“#divTxt”).append(“First Name:Last Name:Remove“);

    however, I cannot get the Remove button to work. With a bit of digging I’m guessing it’s because of the and tags in amongst the form controls, is there any way I can make this work?

    Cheers

  2. oldmateluke Says:

    hah just figured it out! Looks like I pasted the wrong line above anyway. Thanks again this was exactly what I’ve been searching for, and your description/walkthru was very clear and helpful.

  3. oldmateluke Says:

    Argh… is it possible for you to explain how I can now submit these to my database? I have inputs with names studentName1 & studentEmail1, studentName2 & studentEmail2 … studentnameN & studentEmailN, etc which should each be added as rows in my students table.. but I’m at a loss to figure this out. Any help or a point in the right direction, even google search phrase would be great 🙂

  4. mohdshaiful Says:

    @oldmateluke
    hi…if u notice at my example above in the JS code for adding fields, i intentionally name the new inserted fields as name=”txt[ ]” while maintaining a unique id. The idea of naming this way (name=”txt[ ]”) is to simplify processing in the server-side code (e.g. insert to DB).
    So in the server-side code, say PHP, u need to write something to count the elements of $_POST[’txt’] array. Then, using the value u need to construct a while or for loop to process the array, which will be accessible through $_POST[’txt’][0], $_POST[’txt’][1], $_POST[’txt’][2]…
    Hope that helps

  5. mohdshaiful Says:

    Sorry about the single & double quotes messing up the code snippets in this post. Im not quite sure how to solve this thing

  6. sue Says:

    hi shaiful..u did a great job..u rules man…


  7. I read over this and created my own version which would create multiple form sections, each with the ability to create multiple file input fields. You should adapt this a bit, and create a generic function that takes the ID of the affected element, as well as the counter to use. Also, be a bit careful with the WordPress text functions, you’ve got actual quotations (‘’“”) in the code, rather than regular marks (‘”). (Although, I have a feeling they’ll get broken when I post this, anyway, so you won’t even see it.) Try getting a code posting plug-in. There are plenty of great ones out there.

  8. Dennis Says:

    hmmm nice code… i havent tried it yet, but i hav a question regarding the reset button you put in your example. it goes this way, what if i have added an element let say 5 element, i know it has its unique ID ryt? then i press the reset button then add another five element. aha! i have now 10 form element with five unique ID. this is not much a problem but makes the reset button not useful. Thats my own point of view…

  9. Paul Says:

    Hi Shaiful. Great! I love the script and its exactly what i was looking for – Thank You. One comment/question/suggestion… I notice that when you remove elements and then add some new elements the id numbers get out of sequence (due to the previous elements being added) Is there a way to reset that array as to stay in correct numeric order when removing and adding?

    Thanks again!

    pauly_43

  10. Daweb Says:

    Hi everybody, with the last JQuery.js version IE 6 have some little problems. It doesn’t remove and highlitht items…

    Change $(“#divTxt”).append(“Field ” + id + ”   […]

    with:

    $(“#divTxt”).append(“Field ” + id + ”  

    • ahu Says:

      Change $(“#divTxt”).append(“Field ” + id + “ […]

      with:

      $(“#divTxt”).append(“Field ” + id + “

      anything different?


  11. […] dagboek bij 10:50 door christof Vandaag heb ik het eindelijk gevonden. Na het vinden van deze site https://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/ was het onmiddellijk raak. Het maakt gebruik van een apart stukje .js code dat je moet importeren. […]

  12. Norm Says:

    Awesome script, mohdshaiful! I’m trying to integrate this with jQuery Autocomplete Mod (http://www.pengoworks.com/workshop/jquery/autocomplete.htm).

    Could you tell me a good way display rows that are pre-populated? I know how to prepopulate the form fields, I just can’t figure out how to show rows on pageload. I would like to use this to edit records as well as add.

  13. Norm Says:

    One other thing noticed… If the page is refreshed, the row count is incremented.

    Add = Field 1
    Refresh
    Add = Field 2

    Is there any way to reset the count upon refresh?


  14. your website is quite frustrating to read through, difficult to read, the font size is very small and the code that you are reporting it’s nearly impossible to read.

    And I have just a standard resolution (1280×1024)

  15. raja Says:

    hai, its really useful for us.

  16. raja Says:

    how can insert the data in this coding

  17. Samar Says:

    Hi, great job but with IE7 remove button and highlights effects don’t work, please help me!!!

  18. nagendran Says:

    hi, thanks for ur coding,its very useful for my work,but i want display the new divs in upwards not in downwards, pls help to this

  19. Samar Says:

    Hi at all!
    I have a question:
    if I put the demo code in my server dont’ work with IE7, please help me, thx

  20. Cooluck Says:

    For last versions of jQuery and to fix some IE bugs it’s better to use plugin http://www.fyneworks.com/jquery/multiple-file-upload/

  21. shyrez Says:

    great job…may god bless u

  22. Spons Says:

    Hi, great script!.
    But the remove function doesn’t seems to work in IE7 with the latest jquery pack. 1.2.6. any ideas?

  23. Henk de Graaf Says:

    This script isn’t working in IE7 with Jquery 1.2.6., but I found a fix: remove the and it works perfectly.

  24. Henk de Graaf Says:

    ^^ remove the in the append.

  25. Umut Benzer Says:

    thanks! i’ll use this in my projects 🙂

  26. Stefan Says:

    Nice post. Anyway, a few things:
    – there is parseInt, that looks nicer to me than (id – 1) + 2 😛
    – You need to decrease the number of the fields again when you remove a field, if you use the numbers
    – Reloading the page in firefox somehow doesn’t reset the hidden field so that it starts at the number it had before (annoying…)

    • Anderson Says:

      – Reloading the page in firefox somehow doesn’t reset the hidden field so that it starts at the number it had before (annoying…)

  27. Manny Says:

    Hello. Nice job man. I was wondering if you can integrate a chain script into the add new row script. So for every new row, you could select Country and States from db. Thanks.

  28. hebiryu Says:

    the text are too small. anyway. thanks for your tutorial.

  29. marcelpad Says:

    Good work on the post. Just what I was looking for 🙂

  30. justin Says:

    Hi,

    How could i make it so every time the input field is no empty that a new input field automatically gets added instead of having to press add?

  31. Dwi Setiyadi Says:

    Thanks a lot
    Very usefull

  32. Brian Morris Says:

    Thanks a ton. This is just what I was looking for.

  33. Atif Says:

    Hi. This is great, I have a quick question though.
    Right now when I see in your demo, and Click on add, it keeps adding input box, How can I limit it to only 3 input box and once 3 input boxes gets added, the Add button disappear.

    thanks

  34. Kailash Says:

    The quotes don’t make much of a difference as far as I know 🙂 Anyway great job there. Its a great time saver!

  35. donidonix Says:

    great post, but use some syntax highlighting please (^_^)

  36. Craig Says:

    Hello,

    I have an issue… i know that you have not had any comments since 2007 but i thought i would get in touch just to inform you that your script does not work with the latest jquery pack. I can only hope that you still have the enthusiasm to keep this post updated because i really need this for my website, it took me forever to find this script and cant find any alternatives.

    I have another jquery element on the form which relies on the latest jquery pack 😦

    I would bow to you and kiss your feet if you happen to figure out a way round this problem

    Craig

  37. cabezametal Says:

    great example!
    A big thank you from Buenos Aires

  38. raymanexe Says:

    thanks man for this tip… keep posting!

  39. swap Says:

    does not work with the new jquery 1.2.6

  40. Istvan Says:

    Hey 😉
    the script doesn’t work whit the new jQuery. (In IE is the problem). U could optimize for the new jQuery ? Thx

  41. tareq Says:

    Hi,
    Thanx that u have made available this code to add / remove html element using JQuery but their is a mistake in remove javascript method $(id).remove(); , it should be $(‘#’.id).remove(); this is correct one to remove / add element to ur html template.
    with ur code it asks for html element i.e. $(‘div’).remove(); / $(‘div’).add();

    with this change it will add / remove elements

    Thanx & Regards

    cheers 😉
    ***tareq***

  42. tareq Says:

    Syntax for above comment to add / remove
    $(‘#’+id).add();
    $(‘#’+id).remove();
    now it will look for id of give element.

    😉 cheers
    India

  43. Anjan Bhowmik Says:

    Nice post bro! Very helpful. Since u r much experianced with jquery, i think u may b able to help me little bit. I m trying to design an online query with a timer of 10 mins.I want to submit the form automaticaly right after 10 mins. Is it possible to submit the form right after 10 mins?

  44. b4r7 Says:

    it’s exactly what i needed. thank’s mate!

  45. Pepe Says:

    Great! Thanks

  46. Nasko Says:

    So how will this work with IE and the last release of jquery?!?

    Great job!

    Regards

    Nasko

  47. vance Says:

    Great code. I have a problem with the remove function. I have copied and pasted from the demo with all the javascript files. Any advice would be great

  48. vance Says:

    Have just checked on firefox and it works fine. Seems its a explorer issue (version 6) dont know why i still have this version. Strange that on your demo it works fine.

  49. Ben Wong Says:

    Awesome! Thanks this is just what I was looking for!

  50. Kevin Says:

    Can this be modified to allow a predefined number of form fields to be added with non-dynamic field names? For instance, add up to 5 text fields each with a predefined name.

  51. Andy Says:

    Hey there,

    I was wondering if you had this working with the new jQuery library.
    I am trying to do something very similar to you, and found it works perfectly in FF but the remove will not work with the new jQuery library in IE. Your jQuery library is fine, but does not support the new UI for jQuery.

    Any help would be great.
    Thanks,

    Andy

  52. Cool Guy Says:

    Yeah how can set autofocus on the text field when we click add.
    please help me

  53. krembo99.com Says:

    This is a very interesting method, But how can one use it to add a more complex form, not just TXT fields.
    For example a form that contains lists, radio buttons, checkboxes etc…
    I have tried to regex something, but with no success..

  54. joshribakoff Says:

    a = (id – 1) + 2;
    b = id + 1;
    assert( a === b );

  55. jay Says:

    REMOVE functionality is not working with latest jQuery in IE, as mentioned by many others. Can you please fix it.

  56. Wanja Fagard Says:

    Thank you for the script, but can you fix the remove function in IE for the newest jquery pack?

  57. Joshua Says:

    You can simply change the addFormField code.. for example:

    $(‘#id_of_object_before’).add(”); etc etc

    However I’m having problems processing the form. It doesnt seem to send the new form objects true the post.. im going to try a get method now

  58. Bob Says:

    @tareq

    But in the author’s removeFromField function, he passes the whole id, for example, ‘#row1’. Changing it to $(‘#’+id).remove() would add an extra ‘#’ in front.

  59. SuPh Says:

    Finally I found it!!
    Thank you friend.

  60. claudod Says:

    Hello guys. Thanks for this very useful code! It’s really what I was searching for! As I can see from all posts submitted, I’ve had the same problem of many others, using the code with IE. I try to follow your instructions but I can’t resolve the problem anyway:
    I can read some posts like this “remove the in the append” but probably you used a not validable characters in this. I try to do as Tareq wrote, but it isn’t yet working anyway!
    #Please: MAYBE IT COULD BE VERY USEFUL for me and many others TO POST THE WHOLE RIGHT CODE!!!

    thanks to all!!!


  61. It’d be great if it worked with the latest jquery library.

    K.

  62. Marinkina Says:

    1 п. “Не имей сто друзей, а имей сто шекелей” тоже хорошо рифмуется 🙂
    8 п. Ты никогда не потеряешь работу. Когда закончатся фотографии можно размещать рисунки (да хоть бы и конкурс объявить на лучший рисунок Одри (-:), аппликации и фотографии поделок из пластилина…
    9 п. Сто пудов ! 🙂

  63. Dyevergepay Says:

    Да пошленько немного, а так прикольно) я обожаю …)

    здесь видел ет gamebulletin.ru

  64. janlie macdovish Says:

    i think there something wrong with your codes..thats why it cant remove the element. The label tag has no closing tag.
    take a look below:

    var id = document.getElementById(“id”).value;
    $(“#divTxt”).append(“Field ” + id + ” […]

  65. Zachary Cohen Says:

    Hey thanks for such a useful tutorial. I am trying to change it so each added field is a tile upload section. How do I set it so each additional field is “input type=file”??

    THanks

  66. efrg Says:

    wefrgt http://www.linkedin.com/in/dgdfdgf sites like youporno com dasadsa http://www.linkedin.com/in/dgdfdgf youporno arabic dasadsa http://www.linkedin.com/in/dgdfdgf youporno com lite beta dasadsa http://www.linkedin.com/in/dgdfdgf youporno asian

  67. unwrangle Says:

    just to update for step 4: $(id).remove(); doesn’t work (maybe for newer jquery)..

    now u need: $(‘#’+id).remove();

    cheers


  68. There should be a more beautiful way like not just writing the HTML code, but using JQuery to generate the form objects.

    I try to find out.

  69. Jonas Eriksson Says:

    Problem with ie was that the tags wasn’t properly closed:
    function addFormField() {
    var id = document.getElementById(“id”).value;
    $(“#divTxt”).append(“Field ” + id + ” Remove“);
    id = (id-1)+2;
    document.getElementById(“id”).value = id;
    }

  70. Jonas Eriksson Says:

    Trying to paste again… Now with pre.

    	function addFormField() {
    	var id = document.getElementById("id").value;
    	$("#divTxt").append("Field " + id + "  Remove");
    	id = (id-1)+2;
    	document.getElementById("id").value = id;
    	}
    
  71. Jonas Eriksson Says:

    $(“#divTxt”).append(“>p id=’row” + id + “‘<>label for=’txt” + id + “‘>Field ” + id + ” </label><input type=’text’ size=’20’ name=’txt[]’ id=’txt” + id + “‘/> <a href=’#’ onClick=’removeFormField(\”#row” + id + “\”); return false;’>Remove</a></p>”);

  72. Jonas Eriksson Says:

    $(“#divTxt”).append(“<p id=’row” + id + “‘><label for=’txt” + id + “‘>Field ” + id + ” </label><input type=’text’ size=’20’ name=’txt[]’ id=’txt” + id + “‘/> <a href=’#’ onClick=’removeFormField(\”#row” + id + “\”); return false;’>Remove</a></p>”);

  73. Jonas Eriksson Says:

    Ooops, hard to paste correct code, now I think I made it. There it is with correct format. The problem with the original code when I tried in ie7 was that it missed some endtags. and Hth

  74. Rob Says:

    As a few people have been asking how to save information to a database I made an extended tutorial using your original idea, where I get all the dynamic form values and save them to a MySQL database, using a many-many database design. See:

    http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/

    • gtenor Says:

      Now how do you go about remove these dynamically added form elements? I’ve tried many ways, but it don’t work. what’s the best way to do it?

  75. bAxTEr Says:

    Look this

    a = (id – 1) + 2;

    change for

    a++;

    😉

  76. Tijuan Says:

    Javascript errors are not always where you think.
    IE7 triggers errors when html is not well formated.

    So the code can work on IE7 only if you correctly nest your html elements and make sure it is valid (amazing when it comes from IE isn’t it ? 🙂

  77. netmastan Says:

    You are using jquery and still document.getElementById?

    You should use something like this –

    var id = $(“input#id”).val();

  78. lous Says:

    Hey,
    at first nice plugin,
    but where can i change the start id?

    Cause when i get allready 2 or more fields by sql query, than it should start with id 3 or 4, its no prob to add php into js, but i really dont know where i can change the “startid” of the jquery function.

    Hope you know what i mean 😀

    P.S.: Is there another plugin like that?

  79. Balaji Says:

    Hai,

    This seems to be not working in IE 6 & latest versions..the problem is remove the “<label" in append line.it will work,you can use the below code also.

    $("#divTxt").append("Field ” + id + ”   &nbspRemove“);

    happy coding……

  80. Mayank Says:

    bug with “IE7” remove and highlights effects don’t work, please help me!!!

    var rowId = document.getElementById(‘counter’).value;

    $(“#divTxt”).append(“Tagline ” + (parseInt(rowId)+1) + ” Remove“);

    $(“#row” + rowId).highlightFade({
    speed:1000
    });

    rowId = (rowId – 1) + 2;
    document.getElementById(‘counter’).value = rowId;
    };

    function removeFormField(row) {
    $(“#”+row).remove();
    }

  81. rtyucel Says:

    thanks dude,
    this was what i want

  82. Luckylooke Says:

    I played a little with your code and I added a Reorder function after removing field, so it recount numbers and so they are still in right order.. 🙂 Maybe someone should use it so here it is:

    function reorderFormField() {
    var idleng;
    var rows, labels, inputs, anchors;
    var rn;
    document.getElementById(“id”).setAttribute(“value”, “1”);
    id = document.getElementById(“id”).value;
    idleng = $(“[id^=’row’]”).length;
    rows = $(“[id^=’row’]”);
    for (i=0;i<idleng;i++)
    {
    rn = i+1;
    rows[i].setAttribute('id', "row"+rn);
    }
    var labels;
    labels = $("[for^='txt']");
    for (i=0;i<idleng;i++)
    {
    rn = i+1;
    labels[i].setAttribute('for', "txt"+rn);
    labels[i].firstChild.nodeValue="Field "+rn+" ";
    }
    inputs = $("[id^='txt']");
    for (i=0;i<idleng;i++)
    {
    rn = i+1;
    inputs[i].setAttribute('id', "txt"+rn);
    }
    anchors = $("[onclick^='remove']");
    for (i=0;i<idleng;i++)
    {
    rn = i+1;
    anchors[i].setAttribute('onclick', "removeFormField(\"#row" + rn + "\")");
    }
    idleng++;
    document.getElementById("id").setAttribute("value", idleng);
    }

    I have also upgraded a remove function to make similar animation like when you are adding field:

    function removeFormField(id) {
    $(id).highlightFade({color:'red',speed:500,complete:function() {$(id).remove();reorderFormField();}});
    }

    As you see there is reorder function called, you can throw it away if you dont need it 😉

    I hope thi will be useful for someone.. have a nice day 😉

    • ahu Says:

      not work anyway 😦

    • Snowdogg Says:

      Thanks for this! It works great, but I get an error message when I remove. It there something that is incorrect in this code?

    • mohit Says:

      hi there guys. this seems like a great code. i am a newbie and an finding difficult to use this one. i have been able to put up this code on the webserver and it shows me the add,submit and reset fields. now how do i actually add my fields like text input, select combo box, etc and where exactly and also, how do i give it an id so that it can be sent to the next form and processed with mysql. i would appreciate help on this.

  83. Luckylooke Says:

    I solved problem with IE incompability! 🙂 Its just about typing mistakes in code and closing tags 😉 I have closed input tags, add label closing tag, repair paragraph closing tag, and everything is working now. Yeaaaah! 🙂

  84. Prashant Says:

    Thanks a ton, i think this is all what i was searching for last half hrs..

  85. mohdshaiful Says:

    Hi, I’m moving to a new blog and planning to publish an updated version of this post. Feel free to contact me there http://www.stampede-design.com/blog

    Thanks

  86. kumar Says:

    Hi Add as new element works but remove not worksAnd I wish to know to ask the user what should be the name of the new textfield and it should be displayed there and any ideas how to handle these new text fields enter into mysql DB using jsp or servlets
    hope i will get a solution fast
    regards’
    kumar
    hyderabad
    india

  87. Marco Leandro do Prado Says:

    Hi, thank’s brother, your post help me in my project.
    I’m from Brazil.

    in Portuguese – Brazilian:
    Muito obrigado

  88. ritha Says:

    Thanks for the awesome post.

  89. Gergo Toth Says:

    Hi the code is very good, i just have a little problem. When i’m generating more fields as an array, my first index is nothing, then it starts with 1. So i can’t get the data which is on the 0 position.

    Can somebody help me!
    Thx

  90. Gergo Toth Says:

    I got the problem, my code was bad. 😛

  91. Amit Says:

    Wonderful post.. good examples of jquery functions..

    Thanks

  92. najam Says:

    Great…………


  93. waa, saya dah cuba buat
    memang gempak

    terima kasih

  94. Alex Bowyer Says:

    joshribakoff… I thought that too but your assertion doesn’t hold up in this case, id must be a string because id + 1 performs a string concatenation so you get Field1, Field11, Field111 instead of Field 1, Field2, Field3.

    The -1 must be sufficient to force it to count as a number, then add instead of concatenate.

    I am sure there is a more elegant solution than this but I am not a Javascript expert.

  95. Daniel Maier Says:

    Hi, how could I use this “Add/remove form elements” in the same page more than one time?

    I would have to repeat the javascript code?

  96. Tweak Says:

    very useful
    thanks

  97. Balraj Says:

    Hello Friends,

    I am trying to apply your code in my smarty application but after submit posting data I could not get addition form elements. I think smarty dose not recognize add more elements.

    Please help me.
    Thanks

  98. af Says:

    Thank you so much for taking the time to put this demo out there and keeping it out here. 4 years have passed and you have helped yet another person. 🙂


  99. Actually, it’s good, my suggestion is that you should demo your ‘Add/remove form elements using jQuery’ on this site after giving and explaining the code. That’s it! Learning from realistic!

  100. max4ever Says:

    the link is dead

  101. John Says:

    Very useful, thanks. I adjusted it slightly by adding a variable to count how many inputs were originally on the page, and then made it only remove if i > that. Otherwise all your other input fields start to disappear!


  102. very good script but would be better if it would validate the fields as well and also explain how to retrieve those textbox values from server side language like php.
    i’ve found a tutorial at

    http://www.pradipchitrakar.com.np/blog/dynamically-add-remove-textfield.html

    it explains how to dynamically add, remove and validate text field in jquery and fetch the values of textbox in php and jsp/servlet


Leave a reply to Bob Cancel reply