简体   繁体   中英

How to store multiple form data values to a single key in local storage

I have an html form when i submit the form the values are get stored in local storage but what i would like to do is whenever the form is submitted it should store the values in the same local storage but what happens is when i try to do the above approach it takes the last submitted value can anyone tell me how could i use the local storage to use the same key for multiple values.

function addToCSVFile() {
    // Collecting the names
    var name = document.getElementById('firstName').value;
    var middlename = document.getElementById('middleName').value;
    var lastname = document.getElementById('lastName').value;
    var data = {name: name, middlename: middlename, lastName: lastname};
    console.log('Data is', data);
    // alldata.push(data);
    localStorage.setItem('Data', JSON.stringify(data));
    clearData();
    alert("Data Added Successfully", JSON.stringify(data));

}

Use an array and push new values to the array.

The sequence would be something like:

var array = JSON.parse(localStorage.getItem('Data') || '[]');
array.push(dataObject);
localStorage.setItem('Data', JSON.stringify(array));

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