How can I clone, modify, and prepend an element with jQuery?
Asked Answered
F

1

6

I want to clone and prepend a div, however I want to change the prepended div name from preConfi to preConfiXX (eg preConfiA1, preConfiB1) on each iteration. What syntax can I use for this?

/* on initial load,  move default template into each GroupX location */
var groups = ['A','B','C','D','E','F','G']
for (var groupLetter in groups){
    $('#template').clone().prependTo('#placeholder' + groups[groupLetter]);
}


        <!-- ************************** --> 
    <!-- *******  GROUPS   ******** --> 
    <!-- ************************** --> 
    <div id='groupA' class='preGroups'> 
    GroupA
    <div id="placeholderA"></div>
    </div>

    <div id='groupB' class='preGroups'> 
    GroupB
    <div id="placeholderB"></div>   
    </div>

         ....

    <div id='groupF' class='preGroups'> 
    <div id="placeholderF"></div>
    GroupF
    </div>


<div id='template'> 
<input type="radio" data-theme="a" name="preConfi" id="radio-choice-1" value="C" /> 
<input type="radio" data-theme="a" name="preConfi" id="radio-choice-2" value="T" /> 
<input type="radio" data-theme="a" name="preConfi" id="radio-choice-3" value="P" /> 
</div> 
Fatherhood answered 10/7, 2011 at 20:22 Comment(9)
Your question is not clear, can you give us a sample output you want to achieve?Truthful
sorry I don't understand what you're trying to do. change preConfi inside each cloned template?Mould
+1 Need just a little bit more.Corallite
Sorry... I improved my explanation a bit.Fatherhood
+1 Agreed. I think I may understand it but we need more info to be sure.Mould
You're asking to change the cloned id but preConfi is only in the name of a child radio element of the cloned Div. That is why this is confusing.Mould
thanks for additional clean up. Your answer looks bang-on (maybe missing a terminating blacket) I will try it.Fatherhood
.... Actually I am getting myClone is not a function error... I think it should read myClone.prependTo('#placeholder' + groups[groupLetter]);Fatherhood
It works now. Also provided a jsfiddle.Mould
M
10

I'll take a shot at what I think you want:

$(document).ready(function() {
    var groups = ['A','B','C','D','E','F','G'];
    for (var groupLetter in groups){
        var myClone = $('#template').clone();
        myClone.attr("id", "template-"+groups[groupLetter]);

        var index = 1;
        myClone.find("input[type^=radio]").each(function() {
            var myName = $(this).attr("name");
            $(this).attr("name", myName+groups[groupLetter]+index++);
        });

        myClone.prependTo('#placeholder' + groups[groupLetter]);
    }
});

http://jsfiddle.net/a5HB7/3/

Mould answered 10/7, 2011 at 20:38 Comment(3)
Cleaned up a missing end paren.Mould
had an extra () where it shouldn't be.Mould
Don't forget that there should be only one element on a page with any given ID. So you want to change the clone's ID.Mould

© 2022 - 2024 — McMap. All rights reserved.