Clone form and increment

前端 未结 5 429
感情败类
感情败类 2020-12-03 16:21

I have a form below that I want to clone, increment the id(att1) and it\'s inputs, textareas etc and append to the attendees div. Any help much appreciated. Been wrecking my

5条回答
  •  清歌不尽
    2020-12-03 17:19

    I posted this same answer elsewhere, but here I think it applies to this question too.

    I created an 'original' element and hid it on the page. I appended "---" to the value of any attribute that needed to be incremented within any child elements of the original.

    Whenever the user clicked a button to create a clone of the original, I created a clone, then globally replaced "---" with the current index within that clone's HTML. Something like this:

    var $clone = $original.clone();
    var cloneHTML = $clone.html().replace(/---/g, incrementedFieldNum);
    $clone.html(cloneHTML);
    
    // Insert and show the clone after the original
    $original.after($clone);
    

    I used a data attribute to store updated values of incrementedFieldNum (not shown in the code above).

    Hopefully that helps. It's a lot less code and it's a more general solution I think. I had a lot of nested elements that needed to have incremented IDs and names, so a solution like the one from @Fierceblood was impractical.

提交回复
热议问题