About Leros
About Leros

Reputation: 190

How to create local storage?

My website has tabs and within that tab, info cards and a checkbox on the right hand side that highlights the card in a different colour. How can I makes it so that onclick the highlighting is saved even if the page is refreshed or if the page is sent as a link? Full code here: http://codepen.io/johnsonshara/pen/obGjGN (below code not in code pen version)

What I have tried:

function save () {
    var fieldValue = document.getElementById('like').value;
    localStorage.setItem('checkbox', 'fieldValue');
}

function load () {
    var storedValue = localStorage.getItem('checkbox');
    if(storedValue){
        document.getElementById('like').value = storedValue;
    }   
}

And This:

function save() {
if(typeof(Storage) !== "undefined") {
if (localStorage.setItem) {
localStorage.setItem = document.getElementById("like");
} else {
localStorage.getItem = .hasClass.apply;
}
document.getElementById("like").innerHTML = localStorage.toString;
} else {
document.getElementById("like").innerHTML = "Sorry, an error occured.";
}
}

html

<input type="checkbox" class="faChkRnd" onclick="save()" id="like" >    

Upvotes: 3

Views: 2662

Answers (2)

Arashsoft
Arashsoft

Reputation: 2757

or if the page is sent as a link

You should store your data as a url parameter not in the local storage. So anyone that click on the link will get the data.

See this link to know more about using url parameters with JS: How to get the value from the GET parameters?

Upvotes: 0

YaBCK
YaBCK

Reputation: 3029

Check out the following link to see how you can use the local storage:

http://www.w3schools.com/html/html5_webstorage.asp

Quick example code of how it would work:

// Put the object into storage
localStorage.setItem('testObject', "testing");

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

Example using your example code above:

alert(load());

$(document).on("click", "#clickME", function(){
  save();
});

function save () 
{
    var fieldValue = "testString";
    localStorage.setItem('checkbox', fieldValue);
}

function load () 
{
    var storedValue = localStorage.getItem('checkbox');
    if(storedValue)
    {
        console.log("VALUE :" + localStorage.getItem('checkbox'));
    }   
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="clickME">Click me</button>

Upvotes: 3

Related Questions