mercredi 9 décembre 2020

Load a function if checkbox is checked and save the checkbox to localstorage using Javascript or jQuery

Actually I'm a beginner in js coding and I want to create such a code :

User will click on checkbox to check. Then a function will be load if checkbox is checked. Then I want to save the user preferences of checkbox checking using localStorage.

My HTML:

<input type="checkbox" class="loadplayer"></input>
<p id="changedtext"></p>

My Tried Javascript:

var mainDiv = document.querySelector(".main");
var checkBoxes = document.querySelectorAll(".loadplayer");

document.forms[0].addEventListener("change",storeCheckData);

function storeCheckData(){
    for(var i=0; i<checkBoxes.length;i++){
        if (checkBoxes[i].checked){
            localStorage.setItem("checked tab",JSON.stringify({position:i}));
            //Put Your Function Here
          document.getElementById("changedtext").innerHTML = "Its Checked!";
        }
    }
}

function loadCheckData(){
    var checkedTab = localStorage.getItem("checked tab");
  console.log(checkedTab);
  if(checkedTab!=null){
       var temp = JSON.parse(checkedTab).position;
    console.log(temp);
    checkBoxes[temp].checked = "true";
  }
}

loadCheckData();

I don't know what I'm doing wrong here, any help would be appreciated. :)




Aucun commentaire:

Enregistrer un commentaire