How to save user input from a form into JavaScript objects

放肆的年华 提交于 2020-01-06 05:38:06

问题


I'm new to Javascript and I'm having some issues creating a feature. I have an html form which takes in users name and address.

I want to create a function that when the user submits the form that users information is saved into a JavaScript object.

Something like this:

Var person = {

       Name : abc,
       Address: xyz}

I was able to save the information into an object but when ever a new person submits the form the old info is overwritten. Is it possible to create a separate object for every user who submits he form.

Thank you for the help in advance.


回答1:


var a = [];

// On some event
a.push({
  Name: newValue, 
  Address: newValue
});



回答2:


You can change the object you have to an array, then wherever you were populating the object, populate a new object and push it onto the array:

var people = []; // this is where var person was

function event_handler () { // assuming the object gets populated as part of an event
    people.push({
        Name: newName,
        Address: newAddress
    });
}

push pushes the new object onto the end of the array.



来源:https://stackoverflow.com/questions/26439098/how-to-save-user-input-from-a-form-into-javascript-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!