Shaun Mccran

My digital playground

18
A
U
G
2011

Using JQuery to dynamically add form fields to a page

I'd seen a few different ways of dynamically adding form fields to a web page but hadn't ever tried it. I was interested in seeing how exactly you can do this at a technical level, but also how you can manage the users interactions, allowing them to keep adding fields as they complete the previously added ones.

Firstly lets define a few goals:

1. I want to add new form fields to an existing form, and they must have unique ids / names.

2. I want to make sure that a user can keep adding more new fields but only after they have completed the previous added field.

Let's setup the form first.

view plain print about
1<div class="form-label">
2    <label for="static">Static form field</label>
3</div>
4<div class="form-field">
5    <input type="text" name="static" id="static" size="20">
6</div>
7
8<div id="newfields"></div>
9
10<div id="more-link" class="clear-both big"></div>
11
12<div class="form-label"></div>
13<div class="form-field">
14    <input type="submit" name="Action" value="submit">
15</div>

The first form field is a 'normal' static field, nothing exciting going on here. Next there is a div element ''newfields" this is a container for our newly added fields.

Next we have a div "more-link" this contains a JQuery powered link that users will click on to add new fields. I'm creating this in JavaScript so that I can turn the link on and off based on some conditional logic.

Now lets take a look at the JQuery that will populate these divs.

view plain print about
1<s/cript>
2// create an index value    
3var index = 1;
4
5// adds a new field
6function addfield() {
7        index++;
8        var appendStr = '<div class="form-label"><label for="newfield'+index+'">New field no '+index+'</label></div>'
9            appendStr += '<div class="form-field"><input id="newfield'+index+'" name="newfield'+index+'" size="20" class="exit-detect"></div>'
10
11        $('#newfields').append(appendStr);
12        // turn off the click event to create new fields
13        removeStr();
14    }
15
16    // disables the hyperlink
17    function removeStr(){
18        $('#more-link').html('Add field')
19    }
20
21    // enables the hyperlink
22    function addStr(){
23        $('#more-link').html('<a href=javascript:void(0); id=add-field>Add field</a>')
24    }
25
26    $(document).ready(function(){
27
28        // create the link when the dom loads
29        addStr();
30
31        // use live() to create a click event
32        $('#add-field').live('click', function() {
33            addfield();
34        });
35
36        // did the user click out of the new field, does it have a value?
37        $('.exit-detect').live('blur', function() {
38
39            // check if the field length is gt 0
40            if($(this).val().length >
0){
41                // turn the link back on
42                addStr();
43            }
44
45        });
46
47    });
48</script>

There is a fair bit of code here, so we'll break it down. Initially I create an index value. This will be incremented each time we create a new field.

Next we have a function 'addfield', this creates the form elements and appends them into the div 'newfields'. It then disables the hyperlink that creates the fields.

Next there are two functions 'removeStr' and 'addStr' these create or destroy a hyperlink to allow users to make new fields. They are called from other functions here.

Now we are inside our document.ready, so this is going to fire when the DOM has loaded. Firstly we create the link to add fields using 'addStr()'.

Next there is a click event on the selector '#add-field'. This runs the function (addfield) that creates the form fields.

Lastly there is a selector on the element 'exit-detect' that runs a blur event on the form field that was created. It checks that the newly created field has a value in it, if it does then it re-enables the hyperlink, allowing the user to create more fields. In this way a user cannot just click 'add' a dozen times and create a load of blank fields.

Note that most of these selectors are using the live() method to bind an event as the dom elements don't exist on page load.

Follow this link to view a demo of using JQuery to dynamically add form fields.

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
David D Yarbrough's Gravatar Thanks for this detailed article about using JQuery to dynamically add form fields to a page that need these fields. Your tutorial is awesoema nd it is easy to create this form. http://www.essaycenter.biz/ is also good for the generation of the best content.
# Posted By David D Yarbrough | 02/08/2015 11:35
breitling replica's Gravatar With the accepted bread-and-butter crisis that is getting acquainted about the http://www.humanbeans.co.uk apple alone a scattering of humans will be accommodating to absorb abundant on affluence items. There are added acute issues to accord with, all of which charge money; the amount of active is absolutely at an best high. However, humans will consistently appear up with means of arresting during such angular times. To many, giving up on what they accept in is like acute their soul. For instance, we accept humans who cannot let go of their faculty of appearance and fashion. This accumulation of humans will do whatever it takes if alone to advance their faculty of trendiness.Perhaps this is the acumen why the acceptance of the Breitling replica watches continues to acceleration as if in complete affront of what the accepted times appeal - a faculty of thriftiness. Ideally,Breitling is one of the a lot of http://www.lblp.co.uk big-ticket watch brands beneath the sun. The aboriginal adaptation of this amazing alarm can amount one a baby fortune. The Omega Constellation abreast archetypal is based aloft actual abiding watchmaking traditions. Omega replica Constellation provides advanced array of designs - animate and steel-"gold" versions, with annular and square-shaped situations, different punch tints, versions of affected and adventurous models. If you bead a attending at the accident aback again, you will see the anchor adumbration featured by every individual Omega replica Constellation view. The http://www.cvdlipids.com anchor adumbration stands for the apple timekeeping abstracts accustomed by the Omega Business and hints at those instances if attention competitions were organized in the arch European observatories. Omega consistently completes its Constellation accumulating with new watch designs, which cover the chronographs. The Omega replica Constellation wristwatches are all time classicsFree Reprint Articles or blog posts, about they reflect the a lot of accepted trends in appearance and abstruse innovation. The Omega band of men's replica watches defines class, style, and an able-bodied attending for a man. Their affection accumulating is accepted as the James Bond collection.
# Posted By breitling replica | 08/08/2015 00:42
writing a research proposal's Gravatar JQuery is a JavaScript file, so it makes intelligence to have a common sense of JavaScript without jQuery previous to you add it into place.
# Posted By writing a research proposal | 01/09/2015 03:27
Bestassignmentservice.com's Gravatar I would make a go at club meeting in any case, that appears like you have to go out, and meet more individuals or welcome one of your great companions to run with you, and after that meet individuals there.
# Posted By Bestassignmentservice.com | 03/10/2015 03:46
Can you write my paper for me's Gravatar You should utilize my guide on placing report with databases employing jQuery in addition to php in addition to mix the item using this type of guide to produce a amazing dynamic style taking advices through consumer in addition to put the item as part of your databases.
# Posted By Can you write my paper for me | 26/10/2015 02:30
essay writing's Gravatar Query is a JavaScript library, so it bodes well to have a general feeling of JavaScript without query before you include it into spot. With your experience, you won't have any issues with JavaScript, yet spend an hour or two with it before adding query to the blend.
# Posted By essay writing | 13/11/2015 23:14
Assignment Help's Gravatar Thanks for sharing that post with us. I like the way you have presented facts to argue out your case.
# Posted By Assignment Help | 17/11/2015 03:56
academic essays online's Gravatar This jQuery fragment adds replacement participation fields dynamically and stops when it achieve highest.
# Posted By academic essays online | 04/01/2016 02:03
Neil Jakson's Gravatar your blog so informative and awesome . i am regular reader of your blog. your blog increased a lot of my knowledge
# Posted By Neil Jakson | 04/08/2016 01:34
Back to top