Dynamically add field group to form

One of the top searches online by web designer and developers is dynamic content and CMS engines.

Well, i have a secret to share : You no longer have to search for cool and unique solutions, just get familiar with the term “JQuery” and “Bootstrap” and you are good to go.

I will not cover JQuery and Bootstrap here, because these are huge subjects, and there are lots of resources and articles about them everywhere, and i am here to give you solutions wrapped with the highest and most reliable  frameworks. So if you wish to dig further, you are invited to read all about JQuery and Boostrap on your spare time…

In the next few lines i will give you the power to make your forms dynamic by adding fields to it and have the ability to save the content with no effort at all, as if you were doing this all your life.

First, you need to get your HTML know JQuey, and there is a great Google resource for that, so just include the next line in your head block and you are good to go :

Notice that Google gives you the latest version of JQuery resources, in this example, the latest version is 1.10.2, so we include this in our head.
One more thing, we use the min version of the JS script, and not the full responsive one.
you are better using the  .min in your scripts as Google are checking on page loading times. Having all your JS file minified means they will load faster.

Now, we need to add our addField.js script to the HTML head :

We are good to go and add the “brains” to the form.

Before we add the code to the HTML block, lets go over some insights regarding the JS script we added.
We need to configure some constants to the JS script so it will identify the container and logic functions on the HTML block.

var mainFieldsDivId = "fieldContainer";

This is the id of the div that will contain all the dynamically added fields.

var addFieldButtonId = "addFieldBtn";

This is the is of the “add button” that will add new field to the main container.

var hiddenFieldCounterId = "fieldCount";

For the script to know how many fields added (and rearrange fields on delete) we have an hidden counter. This is the counter’s id.

var fieldLabelId = "fieldId";

for each new field added, we give a constant name followed by its index (The number of field added). So, if we added the fifth field, its name will be “fieldId-5”.

var fieldLabelText = "Field";

For each field added, we generate a label with the text in this variable followed by the field index (The number of field added). So, if we added the fifth field, its label text will be “field #5”.

This is the configuration for the script, now we will go over the script’s functionality.
As you might noticed, the script is a JQuery object, launched on the buttons click event. Which button, you ask? The button with the ID configured earlier (The addFieldButtonId variable).

Lets go back to the HTML body block and add the HTML elements. We will add a simple div that will act as our fields container and in it we will put a button and an hidden counter, setting its initial value to 1.

The main div‘s ID is the same id we configured earlier in the JS file under the mainFieldsDivId variable.

The button ID is the same id we configured earlier in the JS file under the addFieldButtonId variable.

The hidden counter ID is the same id we configured earlier in the JS file under the hiddenFieldCounterId variable.

When clicking the “add” button, The JS shoots the click event, and launches an inner function buildFldGroup which will add a label, text field and a delete button to the container div.

The first click will generate this :

Add first field

Add first field

Now lets look at the buildFldGroup function closer…
The function expects 2 parameters :

  1. intId = The id of the added field group.
  2. value = The initial value of the text field. This is optional and most of the time this will be empty. Don’t be afraid, the first line will take care of this for you.

The function will build a new inner div for each field group and add the fields to it.
Notice that the delete button will get a click event handler.
This is crucial, because when click the delete button of for any of the fields, this will remove the field group, reduce 1 from the hidden counter and call another function called rearrangeFields


The rearrangeFields got its own header, and for a good reason too.
When deleting a field group, we want the indexes to be accurate, but we also want the field groups to be arranged.

So, if we delete field group 5, and we had 7 field groups added to our form, we want field group 5 to be deleted, field group 6 to become field group 5, and field group 7 to become field group 6…

Complicated? No really.

The rearrangeFields function is called from the delete button event, passing it the removed field index.

The function will go go over the field group greater than the index given and replace them with new field groups according to the field group’s new location in the hierarchy…

This is it! You can download the script and see for yourself how easy and fun this is.

Oh, You can see a live demo on Youtube now :

82 thoughts on “Dynamically add field group to form

  1. Pingback: cheap oakley sports glasses

  2. Chadwick Casaceli

    I simply want to mention I am very new to blogging and truly enjoyed you’re web site. Likely I’m want to bookmark your blog post . You really come with beneficial posts. Thanks a lot for sharing with us your blog.

  3. real estate tax

    Hi there! І’m at work suгfing around yoսr blog from my new
    apple iphоne! Just wanted to say I love reading through your blog and look forward to all
    your posts! Cɑrry on the eхcellent work!

  4. Charity Collection

    Hola! I’ve ƅeen following your weblog for some time now and finally
    got the bravery to go ahead and give you a shout out frоm Houston Tx!
    Just wanted to tеll ʏou keep up the good worҡ!

  5. Eric

    We are a group of volunteers and starting a new scheme in our community.
    Your website offered us with valuable information to
    work on. You’ve done a formidable job and our entire community will be thankful to you.

  6. buscar mujeres solteras

    Unquestionably believe that which you stated. Your favorite justification appeared to be at the web the
    easiest factor to have in mind of. I say to you, I certainly get irked whilst folks think about
    worries that they just don’t realize about. You managed to hit the nail upon the top as neatly as defined out
    the entire thing without having side-effects , folks can take a signal.
    Will likely be back to get more. Thank you

  7. tao of badass

    Going through a dating guide is just an aspect of lеarning.
    For Vet asѕiѕtance in the Ʀockford area, you can check
    out -. This guіde provides yоu with dating tiρs in aԀdition to breaking up tips as well.

  8. please click the next post

    Hi there, just became alert to your blog via Google, and found that it is truly informative. I am gonna watch out for brussels. I’ll be grateful for those who continue this in future. A lot of folks shall be benefited from your writing. Cheers!|

  9. Yeast No More Review

    Hey, I think your websіte might be havіng browser compatibility issues.
    When I look at your ƅlog in Opera, іt looks fine but when opening in Internet Explorer, іt has some overlapping.
    I just wanted to give you a qսick heaɗs up! Other then that, fantastic blog!

  10. Nancy Shirts

    I just want to mention I am all new to weblog and certainly savored this web site. Probably I’m going to bookmark your website . You actually come with exceptional stories. Cheers for sharing with us your webpage.

  11. Total Hair Regowth Review

    Аppreciating the tіme and energy you put into your blog and
    detailed information you ρresent. It’s greаt to come across a
    blog every once in a while that isn’t the same
    outdated rеhashed information. Fantastic read!
    I’ve bookmaгked your site and I’m including youг RSS feeds to my
    Google account.

  12. Texas Invitational 2014

    This deѕign is steller! You most certainly know how tο keep a reader amused.
    Bеtween your wit and your vidеos, I wаs almost
    movеɗ to start my own blog (well, аlmost…HaHa!) Excellent
    ʝob. I really enjߋyed what you had to say, and mοre than that, ɦow ƴou presented it.
    Too cool!

  13. suburbia toyota of hackensack

    I think that is one of the such a lot vital info for me.
    And i am glad reading your article. However wanna commentary on few common issues,
    The web site style is great, the articles is really excellent : D.
    Good task, cheers

  14. Lindsay Faerber

    I discovered your weblog web site on google and check a couple of of your early posts. Proceed to keep up the very good operate. I simply further up your RSS feed to my MSN Information Reader. Seeking forward to studying more from you afterward!

  15. girls bedroom ideas

    Nice read, I just passed this onto a colleague who was doing a little research on that. And he just bought me lunch as I found it for him smile Thus let me rephrase that: Thank you for lunch!

  16. breast lift

    Pretty section of content. I just stumbled upon your weblog and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I will be subscribing to your augment and even I achievement you access consistently rapidly.

  17. modern outdoor furniture

    Hey There. I found your blog using msn. This is a really well written article. I will make sure to bookmark it and return to read more of your useful info. Thanks for the post. I’ll definitely comeback.

  18. Pingback: Video Productions fort collins

  19. Pingback: weight loss programs

  20. Pingback: vintage buckle video tutorial

  21. Anti Wrinkle Cream

    Hi, i think that i saw you visited my web site so i came to “return the favor”.I’m trying to find things to enhance my website!I suppose its ok to use some of your ideas!!

  22. Pingback: pop over here

  23. insurance

    you’re in reality a excellent webmaster. The website loading velocity is incredible. It kind of feels that you’re doing any distinctive trick. In addition, The contents are masterpiece. you have performed a wonderful job on this topic!

  24. affordable health insurance

    Simply wish to say your article is as amazing. The clearness in your post is just excellent and i could assume you’re an expert on this subject. Well with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please carry on the gratifying work.

  25. traditional furniture

    hi!,I like your writing very much! share we keep up a correspondence more about your article on AOL? I require an expert in this space to resolve my problem. May be that is you! Looking forward to see you.

  26. health care

    I think other web site proprietors should take this website as an model, very clean and great user genial style and design, let alone the content. You’re an expert in this topic!

  27. Tommie Reichelderfer

    Thanks a lot for sharing this enhance people you actually know what you’re talking approximately! Bookmarked. Kindly also check with my site =). We might have a hyperlink trade agreement among us!

  28. garden window

    Wonderful goods from you, man. I’ve understand your stuff previous to and you’re just too wonderful. I really like what you have acquired here, certainly like what you are stating and the way in which you say it. You make it enjoyable and you still care for to keep it wise. I can’t wait to read much more from you. This is actually a wonderful site.

  29. Cheap windows vps

    I’d need to speak with you right here. Which is not some thing It is my job to complete! I like reading a post that could get individuals to feel. Also, thanks for allowing me to comment!

  30. Doctor Hatem Elhagaly

    Can I simply say what a comfort to uncover someone that genuinely understands what they’re discussing on the web. You definitely understand how to bring an issue to light and make it important. More people really need to read this and understand this side of the story. It’s surprising you are not more popular given that you surely possess the gift.

  31. Pingback: Bun B type Beat

  32. Pingback: Real Estate Agent Long Beach CA

  33. Layla

    Awesome content you post here! You can earn some extra money from your website, don’t miss this opportunity, for more info
    simply type in google – omgerido monetize website

  34. Pingback: porno

  35. Elke

    I am curious to find out what blog system you are utilizing?
    I’m experiencing some small security issues with
    my latest site and I’d like to find something more safe. Do you have any


Leave a Reply

Your email address will not be published. Required fields are marked *