Info with checkbox 'checked' property to be saved in local storage

Viewed 952

I would like to save the 'checked' property of a certain checkbox to the local storage, when I refresh the page, the property is lost and the check box is unchecked. What could I change to make this work? I am stuck on this problem for a bit of time. The first part is the JS, and the second part is only the part where i define the checkbox in the HTML. Here is my code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
 
    function myFunction() {
        var isChecked = document.getElementById("chk").checked;
        if (isChecked) {
            //header start
            document.getElementById("logo").innerHTML = "ZMP Polyhymnia";
            document.getElementById("dash").innerHTML = "Dashboard";
            document.getElementById("festival").innerHTML = "Festival";
            document.getElementById("contest").innerHTML = "Contest";
            document.getElementById("jury").innerHTML = "Jury";
            document.getElementById("res").innerHTML = "Results";
            document.getElementById("contacUs").innerHTML = "Contact";
            //header end
            //hero start
            document.getElementById("heading2").innerText = "V International Festival Polyhymnia 2020 Skopje";
            document.getElementById("firstPar").innerText = "International competition Polyhymnia: ";
            document.getElementById("secondPar").innerText = "-Concerts, Music workshops and Seminars";
            document.getElementById("thirdPar").innerText = "-Announcing Laureate of the competition and many other awards from the competition prize fond"
            document.getElementById("fourthPar").style.visibility = "hidden";
            //hero end
            //festival start
            document.getElementById("festivalH").innerHTML = "Festival";
            document.getElementById("festivalPar").innerText = "    International Festival Polyhymnia is a manifestation that is traditionally held for the third consecutive year in the second half of March through the concert halls around the capital. Participants are learners and students from the Republic of Macedonia, neighboring countries and participants from European countries. This year the festival will be held in Skopje from 28.03.2018 until 01.04.2018. This year will be represented several categories ofinstruments for solo and chamber performance (piano, flute, violin, cello, trumpet, clarinet, solo singing)."
            //festival end

        }
        else {
            //header start
            document.getElementById("logo").innerHTML = "ЗМП Полихимнија";
            document.getElementById("dash").innerHTML = "Почетна";
            document.getElementById("festival").innerHTML = "Фестивал";
            document.getElementById("contest").innerHTML = "Натпревар";
            document.getElementById("jury").innerHTML = "Жири";
            document.getElementById("res").innerHTML = "Резултати";
            document.getElementById("contacUs").innerHTML = "Контакт";
            //header end
            //hero start
            document.getElementById("heading2").innerText = "Петти меѓународен фестивал Полихимниа 2020 Скопје";
            document.getElementById("firstPar").innerText = "Во рамките на фестивалот ќе се одржи:";
            document.getElementById("secondPar").innerText = " -Меѓународен Натпревар Полихимниа 2020";
            document.getElementById("thirdPar").innerText = "-Концерт, работилници и семинари за ученици и студенти"
            document.getElementById("fourthPar").style.visibility = "visible";
            //hero end
            //festival start
            document.getElementById("festivalH").innerHTML = "Фестивал";
            document.getElementById("festivalPar").innerText = "     Меѓународниот фестивал на Полихимниа е манифестација која традиционално се одржува трета година по ред во втората половина од месец март низ концертните сали ширум главниот град. Учество земаат ученици и студенти од Република Македонија, соседните земји, но и учесници од Европските земји. Оваа година фестивалот ќе се одржи во Скопје од 28.03.2018 до 01.04.2018 година. Oваа година  ќе бидат застапени повеќе категории на инструменти за соло и камерна изведба  ( пијано, флејта, виолина,виолончело, труба, кларинет, соло пеење )."
            //festival end

        }
    }

    $('#chk').click(function (e) {
        if (e.target.checked) {
            localStorage.checked = true;
        } else {
            localStorage.checked = false;
        }
    })

    $(document).ready(function () {

        document.querySelector('#chk').checked = localStorage.checked

    });
</script>

//this is the HTML PART

   <label class="switch">
     <input type="checkbox" id="chk" onclick="myFunction()">
            <span class="slider round"></span>
    </label>
2 Answers

Go over the API of localStorage, you were using it wrong. Please refer here.

You should use localStorage.setItem() to save the data. And use localStorage.getItem()` to retrieve it.

So your code should look something like that:

$('#chk').click(function (e) {
    if (e.target.checked) {
        localStorage.setItem('checked','true');
    } else {
        localStorage.setItem('checked','false');
    }
})

$(document).ready(function () {

    document.querySelector('#chk').checked = (localStorage.getItem('checked') === 'true')
});

Local storage works by using the getItem() and setItem() methods on the localStorage object. With these methods you can get the currently stored value and set a new value.

Down here I've written two abstractions which make it a bit easier to return the checked value that is stored. It makes sure that the returned value is either true or false.

/**
 * Get the checked state from the localStorage
 * Return the value as a boolean.
 */
function getIsChecked() {
  const storedValue = localStorage.getItem('checked');
  return Boolean(storedValue);
}

/**
 * Set the new checked state into the localStorage.
 * Only accepts a boolean value as state.
 */
function setIsChecked(state) {
  if (typeof state === 'boolean') {
    localStorage.setItem('checked', state);
  }
}

Now read out the stored value and set your checkbox element's checked value.

// Store the element in a constant, as it will probably never change.
const checkBoxElement = document.getElementById('chk');

// Get the current value from the localStorage.
// The result will be true or false.
const isChecked = getIsChecked();

// Set the checked value based on the localStorage value.
checkBoxElement.checked = isChecked;

Updating the value is best done from a change event listener as it will trigger the callback whenever the checkbox checks or unchecks.

// Listen for change event on the checkbox element.
checkBoxElement.addEventListener('change', function(event) {
  const isChecked = event.target.checked;
  setIsChecked(isChecked);
});
Related