Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" >    
like image 857
About Leros Avatar asked Jan 28 '26 01:01

About Leros


1 Answers

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>
like image 182
YaBCK Avatar answered Jan 30 '26 15:01

YaBCK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!