Wesley van Straalen
Wesley van Straalen

Reputation: 45

Retreive object from localstorage jquery

i'm trying to store a object in localstorage with jquery but cannot seem to get a different result as : [object Object].

For instance, how would i be able to consolelog the country in the code below?

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
</head> 

<input type="text" id="text"> 
<button value="save" onClick="setStorage()" id="btn"> Save </button>



<script>
function setStorage(){
    var text = $("#text").val();
    testobj = {'country' : 'testcountry', 'population' : 3}
    localStorage.setItem('storage', {'text' : testobj});

    var retreived = localStorage.getItem('storage');
    console.log('retreived : '  + retreived);
}

</script>

Upvotes: 0

Views: 316

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

localStorage stores strings. For that reason, I store JSON when I'm writing objects and such to storage, using JSON.stringify when storing, and JSON.parse when retrieving:

function setStorage(){
    var text = $("#text").val();
    testobj = {'country' : 'testcountry', 'population' : 3}
    localStorage.setItem('storage', JSON.stringify({'text' : testobj}));

    var retreived = JSON.parse(localStorage.getItem('storage'));
    console.log('retreived : '  + retreived);
}

Upvotes: 1

Related Questions