Scott Selby
Scott Selby

Reputation: 9570

replace id attribute in for loop

I asked another question on this , and got an answer , but still managed to mess it up. I have a for loop , and I want to make clones of a template in my for loop. I would like each id to be replaced with the id + 0 the first time through the loop. So textbox with id tFirstName would be tFirstName0 and id tLastName would be tLastName0 and so on... Then for the next clone , then next time through the loop it would be tFirstName1 , tLastName1, ect..

The problem with this code is that i is adding one for every text box, so in the first template the id's are tFirstName0, tLastName1, ect..

I am looking for - if someone has a suggestion to keep i uniform through out the for loop, then increase , then stay uniform through the next loop

 var NumofClones = (4 * 1);
            for (i = 0; i < NumofClones; i++) {
                var newrow = $('._template').clone().removeClass('_template');
                newrow.find('input[type=text]').attr('id', function (i, oldID) {
                    return oldID + i
                });

                $('.placenewrows').append(newrow);
            }

Upvotes: 4

Views: 171

Answers (1)

xdazz
xdazz

Reputation: 160843

The i in the .attr()'s callback function refer to the parameter i, not the i in the for loop, change the parameter i of the callback function to some others.

 var NumofClones = (4 * 1);
 for (var i = 0; i < NumofClones; i++) {
     var newrow = $('._template').clone().removeClass('_template');
     newrow.find('input[type=text]').attr('id', function (index, oldID) {
         return oldID + i;
     });
     $('.placenewrows').append(newrow);
 }

Upvotes: 4

Related Questions