I am trying to clone a chunk of form element HTML and add it to the DOM. The adding and deleting is working fine, but the newly-added input elements in the chunks are not getting unique ids and names.
I am not able to create unique attribute values for "name" or "id".
For some reason my selector $('#myForm div:last').find('input').each(function(){...}
is not catching these.
<script type="text/javascript">
var uniqueId = 1;
$(function() {
$('.hyperlink').click(function() {
var copy = $("#cosponsorsTemplate").clone(true).appendTo("#addCosponsorSection");
var cosponsorDivId = 'cosponsors_' + uniqueId;
copy.attr('id', cosponsorDivId );
var deleteLink = $('<span class="t_formColumn5"><a class=\"icon delete\"></a></span><div class="clear"></div>');
deleteLink.appendTo(copy);
deleteLink.click(function(){
copy.remove();
});
$('#myForm div:last').find('input').each(function(){
$(this).attr('id', $(this).attr('id') + '_'+ uniqueId);
$(this).attr('name', $(this).attr('name') + '_'+ uniqueId);
});
uniqueId++;
});
});
</script>
</head>
<body>
<div id="container">
<h2>Sponsors Section</h2>
<form action="" id="myForm">
<div id="addCosponsorSection" style="width:900px; margin-left:12px;">
<div id="cosponsors">
<span class="t_formColumn1"><label for="sponsorclubname1">Sponsor club name 1:</label></span>
<span class="t_formColumn2"><input type="text" id="cosponsorcontact" name="cosponsorcontact" placeholder="Name" title="Co-sponsor contact" /></span>
<span class="t_formColumn3"><input type="text" id="cosponsoremail" name="cosponsoremail" placeholder="Email" title="Co-sponsor email" /></span>
<span class="t_formColumn4"><input type="text" id="cosponsorphone" name="cosponsorphone" placeholder="Phone" title="Co-sponsor phone" /></span>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<p><span class="hyperlink">+ cosponsor</span></p>
</form>
<!-- Start Template to Clone -->
<span style="display:none">
<div id="cosponsorsTemplate">
<span class="t_formColumn1"><label for="sponsorclubname1">Sponsor club name</label></span>
<span class="t_formColumn2"><input type="text" id="cosponsorcontact" name="cosponsorcontact" placeholder="Name" title="Co-sponsor contact" /></span>
<span class="t_formColumn3"><input type="text" id="cosponsoremail" name="cosponsoremail" placeholder="Email" title="Co-sponsor email" /></span>
<span class="t_formColumn4"><input type="text" id="cosponsorphone" name="cosponsorphone" placeholder="Phone" title="Co-sponsor phone" /></span>
</div>
</span>
<!-- End Template to Clone -->
</body>
</html>
action=script in order. If you're processing with PHP on the server, append[]to your input'sname(name="cosponsoremail[]") and it will automatically be parsed into an ordered array.