1

Hi I am having a problem with my code hope somebody can help me with it.

I have a HTML file with two textboxes with id:name and another one with id:lname, and a submit button. When I press the button it executes this (function add) which is in a separate file.

var person = {}, people = [];

function add(){

  person.name = document.getElementById('name').value;
  person.lastname = document.getElementById('lname').value;
  people.push(person);
  console.table(people);

}

It seems to work fine the first time (It saves the values into the object and then into the array) but when I change the textboxes and press the button again, instead of saving the new values into the next position in the array it rewrites both positions with this new input duplicated

1
  • at the top of add(), start with person = {}. Or better yet, use a local variable instead of a global one. Commented Jun 13, 2018 at 2:54

3 Answers 3

1

It is happening because you are having the same reference of the object person for all positions in the array. Because of which whenever you change the value of person, it gets updated at all the places it being used. You have to create a reference for each new add operation. Try following

function add(){
  person = {}; // -------------- Add this line here
  person.name = document.getElementById('name').value;
  person.lastname = document.getElementById('lname').value;
  people.push(person);
  console.table(people);

}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the quick response, I corrected my code and it worked just fine.
@Marcelo - Good to hear that :)
0

This could be a scope issue. By putting your person object declaration in your function like Marcelo suggested, you may resolve this. You're thinking that a new object is being cloned each time, but in fact it seems that the same object is being overwritten with new values. If you ran a for loop and saved your iterator to the array each time, you'd find that in the end you'd only have the last value. So it goes.

Comments

0

just initiate the var inside the function, so it would be able to update them every time you call the function

function add(){
  var person = {}, people = [];
  person.name = document.getElementById('name').value;
  person.lastname = document.getElementById('lname').value;
  people.push(person);
  console.table(people);

}

1 Comment

This is wrong. Everytime you add, array will be reset which means at any point of time there will be maximum 1 value in the array which is not what the OP wants.

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.