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.

68 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 + “  


  11. [...] dagboek bij 10:50 door christof Vandaag heb ik het eindelijk gevonden. Na het vinden van deze site http://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 :P
    - 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…)

  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


Leave a Reply