Dan
Dan

Reputation: 5986

Add number to increment value of id attribute with cloned jQuery object

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!

Upvotes: 0

Views: 2303

Answers (1)

charlietfl
charlietfl

Reputation: 171679

Your use of this is out of context. Am using attr(function(index, attr){}) to manage the ID's

// 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
        var numberOfAdditionalAuthors = $('.other-authors').length/*.toString()*/;// toString() not needed
        markUpToClone.find('input').val('').removeAttr('disabled')
        // Ensure cloned inputs have unique id attributes
                .attr('id', function(i, id){
                        return id + numberOfAdditionalAuthors;
                });


        // Append emptied clone
        jQuery('#otherauthorscontainer').append(markUpToClone);
        return false;
    });

Upvotes: 2

Related Questions