简体   繁体   中英

How to retrieve the value stored in localstorage?

var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
        $checkboxes = $("#list :checkbox");

    $checkboxes.on("change", function(){
        $checkboxes.each(function(){
            checkboxValues[this.id] = this.checked;
        });
        localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    });

I am using the code above to store the data into local storage.

{"2":false,"3":false,"4":true}

The data stored in the local storage. How can i get only the value 2 or false? I want to collect the data in the local storage and stored into an array during submit the form.

var items=[];
$.each(checkboxValues, function(key, value) {
            if(value===true){
                $("#" + key).prop('checked', value);
                items.push(key);
            }
        });

The code seem like got problem during submit which caused integrity constraint duplicate entry when store the data to database. I am using ajax to post the data to server and store the data. Is there anything wrong with my code?

Use the below code to access the checkboxValues object. You need to parse it.

var obj = JSON.parse(localStorage.getItem("checkboxValues"));

To access "2", use obj["2"] .

var obj = {"2":false,"3":false,"4":true};
localStorage.setItem('checkboxValues',JSON.stringify(obj));
var storedObject = JSON.parse(localStorage.getItem('checkboxValues'));
console.log(storedObject["2"]);

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