0

I'm trying to build a function to add elements (taken from input fields) in array:

function printPeople(idUser){
    var name = $('#name').val();
    var surname = $('#surname').val();
    var age = $('#age').val();

    var people = []; 


    people.push({
                    "id": idUser,
                    "name": name,
                    "surname": surname,
                    "age": age
});

Everytime I press button "subscribe" I need to add new information in the array, my goal is obtain an array like this:

[{
"id": id,
"nome": name,
"cognome": surname,
"age": age
},
{
"id": id,
"nome": name,
"cognome": surname,
"age": age
}, etc]

In my case I created an empty array and then I add the elements, but everytime I press the button, array becomes empty again...the array doesn't exist outside of the function, so I need to create it at the beginning (and so the array will be empty everytime I call the function..). Any help?

2 Answers 2

3

Because your array is in the function scope, so every time it creates a new array. Just declare your array outside of the function.

 var people = []; 

function printPeople(idUser){
    var name = $('#name').val();
    var surname = $('#surname').val();
    var age = $('#age').val();

    people.push({
                    "id": idUser,
                    "name": name,
                    "surname": surname,
                    "age": age
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0

The function scope recreates a new array when you call the function, so the best way to handle this will be to declare the function outside

var people = [];

function printPeople(idUser){
    var name = $('#name').val();
    var surname = $('#surname').val();
    var age = $('#age').val();   

    people.push({
                    "id": idUser,
                    "name": name,
                    "surname": surname,
                    "age": age
   });
}

Also you can save to local storage so when you refresh you get the same array back.

To Save: localStorage.setItem('peopleArray', JSON.stringify(people));

To Get: JSON.parse(localStorage.getItem('peopleArray'));

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.