Marcelo
Marcelo

Reputation: 23

Javascript Adding data to array not working quite good

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

Upvotes: 1

Views: 41

Answers (3)

mooga
mooga

Reputation: 3317

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);

}

Upvotes: 0

Bezlonir
Bezlonir

Reputation: 66

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.

Upvotes: 0

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

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);

}

Upvotes: 1

Related Questions