Cloning Form and Magnification ID

Consider the following view:

<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> 

Using Javascript (and jQuery), what would be the easiest way to clone the entire form and increment each individual identifier inside to ensure uniqueness.

Using jQuery, I would suggest that you first hide the form using clone() and iterate through the cloned id objects and add a new id fieldname1 , fieldname2 , etc. However, my knowledge of jQuery is not too big, and this project almost kills me.

Any help would be great!

+6
javascript jquery
source share
2 answers

You would clone() it, and before attaching the cloned element to the DOM, you would skip and add a number to each id .

 (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 .

It starts at 0 , but you can easily run count with 1 .

You can also use closure if you want, 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 .

+14
source share

Here is a solution without updating any identifiers:

  • Give all forms the same class
  • Give all fields a name
  • Refer to cloned forms for all forms with class
  • Refer to the fields with their name

Example: How about providing each cloned form with a different identifier and then using name for each input element?

 <form class="theForm"> <input type="password" name="password" /> </form> 

Then clone it with

 container.append($('.theForm:first').clone()); 

(or cache the first form in a variable).

Finally, access the input fields with:

 $('form.theForm:eq(0) [name=password]') // password from first form $('form.theForm:eq(1) [name=password]') // password from second form ... 

If selector search efficiency is a factor here, then there are several trivial ways to speed it up, like caching variables using different forms, caching $('.theForm') and using eq () , etc.

JsFiddle example here: http://jsfiddle.net/orip/dX4sY

+1
source share

All Articles