0

I am creating a form page in which I have 3 input fields:"fname","emailId","phoneNo".

Now I am storing them in localStorage everytime the user enters the details in the form page but the object is getting overwritten. The script for it is:

<script>
$(document).ready(function(){

    var jsonArr=[];
    $('#addVendor').submit(function(){

        var fname=$('#addVendor').find('input[name="first_name"]').val();
        var emailId=$('#addVendor').find('input[name="email_id"]').val();
        var phoneNo=$('#addVendor').find('input[name="phone_no"]').val();
        var jsonObj={};
        jsonObj["fname"]=fname;
        jsonObj["emailId"]=emailId;
        jsonObj["phoneNo"]=phoneNo;
        jsonArr.push(jsonObj);
        localStorage.setItem("userInfo", JSON.stringify(jsonArr));
    });

});
</script>

The format getting saved in the localStorage is:

[{"fname":"hello","emailId":"hello","phoneNo":"4564564"}]

And if I try to append another object to it, it is not appending but overwriting to it and not adding to it. How can I append the object to the one already in the localStorage?

2 Answers 2

2

In your code you are simply replacing the storage data with jsonArr variable data. Localstorage stores data in the form of string. So in order to append to it you need to first fetch the data parse it and append and stringify and store it again

var localStorageData = JSON.parse(localStorage.getItem("userInfo"));
 localStorageData.push(jsonObj);
 localStorage.setItem("userInfo", JSON.stringify(localStorageData));
Sign up to request clarification or add additional context in comments.

Comments

0

You need to first read the content of local storage in the jsonArr, as you are starting with empty array, it is getting overridden.

Instead of:

 var jsonArr=[];

Use:

 var jsonArr=localStorage.getItem("userInfo");

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.