Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone form and increment ID

Consider the following form:

<form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="file" id="file"/>
    <input type="hidden" id="hidden"/>
    <input type="image" id="image" />

    <input type="password" id="password" />
    <input type="radio" id="radio" />
    <input type="reset" id="reset" />
</form>

Utilizing Javascript (and jQuery), what would be the easiest way to clone the entire form and increment each individual id within, to ensure uniqueness.

Using jQuery I would assume you would clone the form initially via clone() and iterate through the cloned objects id and add the new id fieldname1, fieldname2 etc. However, my knowledge of jQuery isn't too great and this project is almost killing me.

Any help would be great!

like image 560
Russell Dias Avatar asked Mar 14 '11 11:03

Russell Dias


People also ask

How to clone a form in JavaScript?

You would clone() it, and before attaching the cloned element to the DOM, you'd run through and add the number to each id attribute. (function() { var count = 0; window. duplicateForm = function() var source = $('form:first'), clone = source. clone(); clone.

How do I clone a div?

To clone a div and change its id with JavaScript, we can use the cloneNode method on the div. Then we can set the id property of the cloned element to set the ID. to add the div.


1 Answers

You would clone() it, and before attaching the cloned element to the DOM, you'd run through and add the number to each id attribute.

(function() {
    var count = 0;

    window.duplicateForm = function()

        var source = $('form:first'),
            clone = source.clone();

        clone.find(':input').attr('id', function(i, val) {
            return val + count;
        });

        clone.appendTo('body');

        count++;
    };

})();

jsFiddle.

This one starts with 0, but you could easily start count with 1.

You could also use a closure if you wanted, i.e.

var cloneForm = function(form, start) {
   start = start || 0;

   return function() {
        var clone = form.clone();

        clone.find(':input').attr('id', function(i, val) {
            return val + start;
        });
        start++;

        return clone;
    };
};

Then you would do...

var cloneContactForm = cloneForm($('#contact-form'), 5);

// Now I want to clone it and put it somewhere.
$(cloneContactForm()).appendTo('body');

jsFiddle.

like image 154
alex Avatar answered Oct 02 '22 12:10

alex