Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

javascript - Clone in JQuery and adding unique IDs for each

I'm creating a simple web app, where users come in; make a selection from drop down boxes and enter some text. Once this is completed, users press a "generate" button which will show them the resulting concatenated string (shown in a <span>), which users can then copy and paste. I've got it to work for one row no problem.

But what I am now trying to achieve is to have an "add row" button, which the user can click, that will replicate the row above. What I'm having trouble with is making sure that once the row is replicated and the generate button is clicked, the copied <span> will just populate the same values as the previous <span>.

UPDATE: So I've managed to use the clone() function from JQuery to copy the row and apend it underneath. Is it possible to change the ID's for each element that is copied, including the id of the form. i.e. so that when it's copied, the form that it's copied to will be called say, "Form1"

JS Fiddle of what I have is here:

http://jsfiddle.net/XJEAn/

UPDATE 2: Essentially I need something similar to this but for the code that I've tried!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

i've updated your fiddle to give the new forms unique id's

http://jsfiddle.net/zq3AN/

it's probably not exactly perfect, but should get you going in the right direction.

var uniqueId = 1;
$(function() {
     $('.addRow').click(function() {
         var copy = $("#original").clone(true);
         var formId = 'NewForm' + uniqueId;
         copy.attr('id', formId );


         $('#campaign').append(copy);
         $('#' + formId).find('input,select').each(function(){
            $(this).attr('id', $(this).attr('id') + uniqueId);

         });
         uniqueId++;  
     });
});

basically you copy the form, change it's id, and append it to the div. then you look form all the inputs and selects and append the same uniqueId parameter to their ids.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...