1) Preamble. I have a link that fire a jQuery method for cloning a div that contains a bunch of selector and all is within form.
2) The html code:
<a href="" id="cloneMethod">Fire</a>
<form method="post" action="">
<div class="colneDivs">
<input type="text" name="1"/>
<input type="text" name="2"/>
<select name="3"></select>
<textarea rows="3" cols="5" name="4"/>
<input type="text" name="5"/>
< ... and so on .../>
</div>
</form>
3) The script:
var iLast, nrCamp, cat, temp, cateCampuri;
$('#cloneMethod').on('click', function(){
$('.cloneDivs:last').clone().insertAfter('.cloneDivs:last');
iLast = $('.cloneDivs:last').find('input:last');
nrCamp = parseInt(iLast.attr('name'))+1;
modiNume(nrCamp);
});
function modiNume(cat){
temp = $('.cloneDivs:last');
cateCampuri = temp.length;
for(i=0; i < cateCampuri; ++i ) {
temp.eq(i).attr('name',cat+i);
}
}
4) The problem.
a) Any idea for:
iLast = $('.cloneDivs:last').find('input:last');
to change:
.find('input:last');
in something general like:
.find('*:last');
I try:
.find('*').last()
and it doesn't work.
b) I want to auto-change selectors name and this part:
for(i=0; i < cateCampuri; ++i ) {
temp.eq(i).attr('name',cat+i);
}
from method modiNume doesn't work. So any idea will be appreciated.
Edit: I made a jsFiddle here: http://jsfiddle.net/JC4dv/1/
There is no auto function to rename. I would suggest you to set an Id like txtname_0, txtDesc_0. and Use following code to clone
<a href="#" id="cloneMethod">Fire</a>
<div class="colneDivs">
<input type="text" id="txtName_0"/>
<input type="text" id="txtId_0"/>
<select id="txtSelect_0"></select>
<textarea rows="3" cols="5" id="txtDesc_0"/>
<input type="text" id="txtTest_0"/>
</div>
and Jquery code:
$('#cloneMethod').on('click', function(e){
e.preventDefault();
var clonedHtml = $('.colneDivs:last').clone(true, true).get(0);
var newId = $('.colneDivs').length;
console.log(newId);
$(clonedHtml).find("*").each(function(index, element) {
if (element.id || element.name) {
var matches = element.id.match( /(.+)_\d+/ );
if (matches && matches.length >= 2) {
var splitedId = matches[1].split('_');
var elementId = splitedId[splitedId.length - 1];
element.id = elementId + "_" + newId;
}
if (element.name) {
element.name = element.id;
}
}
});
$(clonedHtml).insertAfter('.colneDivs:last');
});
Here if fiddle link