-2

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?

13
  • This looks like it should work. Are you sure arrayFields has the correct values? Commented Feb 14, 2017 at 21:00
  • What is arrayFields??? Plus you should use each! What you do is each time you fetch all .massive elements an change their names! Commented Feb 14, 2017 at 21:02
  • you're always modifying all matching elements... that clearly isn't going to do what you want. Commented Feb 14, 2017 at 21:02
  • @MattSpinks i've gone throught my code to check if that's the case, but it isn't Commented Feb 14, 2017 at 21:03
  • @KevinB What am I doing wrongly, please? Commented Feb 14, 2017 at 21:04

1 Answer 1

1

You should use each to affect all of them like this:

var n = parseInt(cloned + 1);
var nElement = $('.clone').clone().attr('id','clone' + n);

nElement.find('.massive').each(function(index) {
    $(this).attr('id', arrayFields[index] + n)
           .attr('name', 'massive[' + arrayFields[index] + n + ']');
});
Sign up to request clarification or add additional context in comments.

1 Comment

I have no idea why i never thought of this approach! Thanks @Ibrahimmahrir for saving me hours of stupidity!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.