1

I try to use each() function on my DOM to get field dynamically added. But I hava a probleme with this code :

  var nouvelle_entree=new Object();
    $('div[name="declaration-ligne-entree"]').each(function () {
    nouvelle_entree.name=$(this).children('input[name="system-input-name"]').val();
    nouvelle_entree.values=$(this).children('input[name="system-input-valeur"]').val().split(",");
    console.log(nouvelle_entree);
    mockSystem.input.push(nouvelle_entree);
    });
    console.log(mockSystem.input);

The push function always push the last child and not the other but on my console log in have the good values.

log 1 : {name: "a", values: Array(1)}

log 2 : {name: "b", values: Array(1)}

log 3: [

{name: "b", values: Array(1)}

{name: "b", values: Array(1)}

]

Why ?

1
  • Short answer is you are pushing the exact same object into array each time, and overwriting it's values every iteration of the loop Commented Dec 16, 2017 at 16:39

1 Answer 1

3

Why ?

Since in every iteration you're overwriting the same object nouvelle_entree.

You need to define the object nouvelle_entree in every iteration not just the first time, else the variable will always contains the informations of the last iteration, e.g :

$('div[name="declaration-ligne-entree"]').each(function() {
  var nouvelle_entree = {};

  nouvelle_entree.name = $(this).children('input[name="system-input-name"]').val();
  nouvelle_entree.values = $(this).children('input[name="system-input-valeur"]').val().split(",");

  mockSystem.input.push(nouvelle_entree);
});

console.log(mockSystem.input);
Sign up to request clarification or add additional context in comments.

Comments

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.