Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to loop through input fields with an each loop, add other form data to an array and then add that input value to the form data already in the array.

It seems to be basically working but every time I set the input it sets that value in all the entries with that name in the array. Any ideas about where my logic is going sideways?

$(this).next('tr').children('td').each(function () {
        input = $(this).children('input');
        units[i] = unit;
        units[i]['barcode'] = input.val();
        i++;
 });

Output object: Object {0: Object, 1: Object} 0: Object barcode: "789" qty: "3" size: 15 status: "received"

1: Object barcode: "789" qty: "3" size: 15 status: "received"

The input.val() is different on each iteration of the each loop, it just assigns the last value to all barcode entries.

share|improve this question
2  
What is unit and i? –  Shomz Jan 14 at 0:28
    
Assuming unit is an object defined before your loop, you're assigning every array element to reference the same object. You need to add some code to create a new object on each iteration. –  nnnnnn Jan 14 at 0:31
    
i is just a counter set to 0 before the loop, unit is an object defined before the loop. If I'm just assigning the same object over and over and that's why the barcode is being reassigned, is there a good way to deal with this? unit is base data that the barcode is tagged on to. –  cholisky Jan 14 at 0:33

1 Answer 1

up vote 0 down vote accepted

You can use extend() with an empty object to clone the unit object so that each array doesn't refer to the same instance:

$(this).next('tr').children('td').each(function () {
        input = $(this).children('input');
        units[i] = $.extend({}, unit);
        units[i]['barcode'] = input.val();
        i++;
 });

This should work fine now with each object unique, including the barcodes.

share|improve this answer
    
That's the ticket! Thank you! –  cholisky Jan 14 at 0:44
    
You're welcome! :) –  Shomz Jan 14 at 0:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.