简体   繁体   中英

function to add input values in array in javascript/jquery

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM