I know this question already has an answer here: Javascript array with for loop, returns only last element, but I haven't found an answer to my particular case! I am cloning a particular section of a form with input fields and each input field has a unique id and am using these ids in an array: var arrayFields = ['streamsource','amountgen','running_cost','taxdue','periodrange']; so that when I clone the parent div of this form fields, the IDs and name attribute of each input field, corresponding to the current element of the array above gets updated with the current increment value of the parent cloned container. Only the name attribute of the form field as well as the form field ID attribute, corresponding to the last element of the array is what is affected, and instead of incrementing only the corresponding form field, the name, ID attribute of all the form fields are replaced by the last array element + the parent cloned container increment value:
var n = parseInt(cloned + 1);
var nElement = $('.clone').clone().attr('id','clone' + n);
for(var i = 0; i <= (arrayFields.length - 1); i++){
nElement.find('.massive').attr('id',arrayFields[i]+n);
nElement.find('.massive').attr('name','massive['+arrayFields[i]+n+']');
}
How do I get this to work as it should?
arrayFields??? Plus you should useeach! What you do is each time you fetch all.massiveelements an change their names!