I'm cloning a set of form input elements using jQuery 1.7.2. Each input element has an id attribute. I want the cloned elements to use the same id attributes as the source elements but with a number appended to them to make them unique.
The code I have is this:
// Add additional author fields
jQuery('#addanotherauthor a').click(function () {
// Clone 'other author' group of fields
var markUpToClone = jQuery('.other-authors').clone();
// Set all input values of cloned mark-up to empty, remove 'disabled' attribute
markUpToClone.find('input').val('').removeAttr('disabled');
// Ensure cloned inputs have unique id attributes
var numberOfAdditionalAuthors = $('.other-authors').length.toString();
markUpToClone.find('input').attr('id', $(this).attr('id') + numberOfAdditionalAuthors);
// Append emptied clone
jQuery('#otherauthorscontainer').append(markUpToClone);
return false;
});
When I run this, the id attributes of the cloned elements become 'undefined1', 'undefined2' etc. The funny thing is if I do this:
markUpToClone.find('input').attr('id', numberOfAdditionalAuthors);
it returns an id of the correctly incremented number. And if I do this:
markUpToClone.find('input').attr('id', $(this).attr('id'));
it returns an id identical to the source value. But when I try to put the two together:
markUpToClone.find('input').attr('id', $(this).attr('id') + numberOfAdditionalAuthors);
I get the 'undefined1' problem.
Can anyone see where this is failing and suggest a fix?
Thanks folks!
atag hasID, I think no$(this).attr('id')in this context would get the id of the input in the clone, not the id of theatag being clicked. How can I just appendnumberOfAdditionalAuthorsto the id attribute of all cloned input tags?