Save checked checkboxes and load them when page reloads

Asked

Viewed 354 times

2

I would like the checkboxes that have been marked to be saved and loaded whenever the page is reloaded or opened again, in addition, in their place there will be icons referring to the options.

I made a function in java script that loads the functions when the page opens, using localStorage but is not working. Could you help me please?

new html.

 <div class=" tab-pane active grid-container" id="biblio" align="center">

        <div id= "consulta0" class="toggle div-inline"  style="display:" > 
          <input type="checkbox" id="consultar-acervo" data-id="consultar-acervo"  name="toggle">
          <label for="consultar-acervo"></label>
          <p class= "nomeToogle"> Consultar Acervos</p>
        </div>

        <div id= "consulta1" class="toggle div-inline" style="display:" >
          <input type="checkbox" id="consultar-reserva" data-id="consultar-reserva" name="toggle"> 
          <label for="consultar-reserva"></label>
          <p class= "nomeToogle"> Consultar Reservas</p> 
        </div>

        <div id= "consulta2" class="toggle div-inline" style="display: ">
          <input type="checkbox" id="renovar-emprestimo" data-id="renovar-emprestimo" name="toggle">
          <label for="renovar-emprestimo"></label>
          <p class= "nomeToogle">Renovar Empréstimos</p> 
        </div>

        <!-- Icones de Biblioteca-->

          <div id = "zoom0" class="div-inline zoom" style="display:none">
          <a href="https://siga.ufvjm.edu.br/index.php?module=biblioteca&mode=compatibilidade&action=main:pesquisasimples" data-toggle="tooltip" data-placement="top" title="Consultar Acervo" target=“_blank”>
            <img src="../images/biblioteca/consultar-acervo.png" style="width:40%" data-id="consultar-acervo" name="icons">
          </a>
          <p class= "nomeToogle"> Consultar Acervos</p>
        </div>

        <div id = "zoom1" class="div-inline zoom" style="display:none">
          <a href="http://siga.ufvjm.edu.br/index.php?module=biblioteca&mode=compatibilidade&action=main:resusuario" data-toggle="tooltip" data-placement="top" title="Consultar Reserva" target=“_blank”>
            <img src="../images/biblioteca/consultar-reserva.png" style="width:40%" data-id="consultar-reserva" name="icons">
          </a>
          <p class= "nomeToogle"> Consultar Reservas</p>
        </div>

        <div id = "zoom2" class="div-inline zoom" style="display:none">
          <a href="http://siga.ufvjm.edu.br/index.php?module=biblioteca&mode=compatibilidade&action=main:renovusuario" data-toggle="tooltip" data-placement="top" title="Renovar Empréstimo" target=“_blank”>
            <img src="../images/biblioteca/renovar-emprestimo.png" style="width:40%" data-id="renovar-emprestimo" name="icons">
          </a>
          <p class= "nomeToogle"> Renovar Empréstimo</p>
        </div>

    </div>

functions.js

        window.onload = function() { //executa o JavaScript imediatamente após a página ser carregada

    function checar(){

        var checa = document.getElementsByName("toggle");
        var img = document.getElementsByName("icons");


        var numElementos = checa.length;
        var i = 0;

        while (i <= numElementos){

            if(checa[i].checked == true){

                var dataCheckbox = checa[i].dataset.id;
                var dataImage = img[i].dataset.id;

                if (dataCheckbox[i] == dataImage[i]){

                   document.getElementById("zoom"+i).style.display = 'inline-block'; // mostra imagem
                   document.getElementById("consulta"+i).style.display = 'none'; // oculta checkbox marcada
                   document.getElementById("aplica").style.display = 'none'; // oculta botão aplicar
                   document.getElementById("edita").style.display = 'inline'; // mostra botão editar
                   document.getElementById("cancela").style.display = 'none'; // oculta botão cancela

                }

        //a partir daqui salva os checkbox marcados pelos usuários

        var opc = localStorage.getItem("checa[" + i + "]"); //verifica se há alguma opc no localStorage

        if (opc == null){
            break;
            }
        alert("deu");

        //grava as opc no localStorage
        localStorage.setItem("checa["+ indice +"]", checa);
        localStorage.setItem("img["+ indice +"]", img);
        indice++

            }
            else{
                document.getElementById("consulta"+i).style.display = 'none'; // oculta checkbox marcada
            }

            i++;
         }
    }

    document.getElementById('aplica').onclick = checar; 



            //função que carrega os ícones na tela de acordo com as opções salvas 
            var checa = document.getElementsByName("toggle");
            var img = document.getElementsByName("icons");
            var numElementos = checa.length;
            var b=0;

            for (i=0; i <= numElementos; i++){
                var opc = localStorage.getItem("checa[" + i +"]"); //verifica se há opc
                if(opc == null){
                    break;
                }

                var dataCheckbox = checa[i].dataset.id;
                var dataImage = img[i].dataset.id;

                if (dataCheckbox[i] == dataImage[i]){

                    document.getElementById("zoom"+i).style.display = 'none'; // oculta imagem
                    document.getElementById("consulta"+i).style.display = 'inline-block'; // mostra checkbox marcada
                    document.getElementById("aplica").style.display = 'block'; // mostra botão aplicar
                    document.getElementById("edita").style.display = 'none'; // oculta botão editar
                    document.getElementById("cancela").style.display = 'inline-block'; // mostra botão cancela

                }

                else{
                    document.getElementById("consulta"+i).style.display = 'inline-block'; // mostra checkbox marcada
                }


            }

};
  • Do not create a localStorage for each item... create only 1 and save the options in string format.

  • Thanks for the suggestion, dvd, I searched for it here in the forum and I found a solution given by you in another topic. I tried to modify to my context and add, in the check() function, only it still doesn’t work, look how it turned out:

  • Document.addeventlistener("Domcontentloaded", Function(){ var checkbox = Document.querySelectorAll("input[type='checkbox']"); for(var itemCheck){ item.addeventlistener("click", Function(){ localStorage.query ? localStorage.query = localStorage.consulta.indexof(this.id+",") == -1 ? localStorage.query+this.id+"," : localStorage.consulta.replace(this.id+",","") : localStorage.query = this.id+","; }); }

  • if(localStorage.query){ for(var itemCheck){ item.checked = localStorage.consulta.indexof(item.id+",") != -1 ? true : false; } } });

  • No, I’m using javascript. With regard to the images, it goes like this: after the user chooses the checkbox, I check the ones that are marked and replace them with icons referring to the functionalities, the ones that were not marked tbm are hidden from the screen, but they will not have their icons shown. That function I’ve done, just tried to use it to save those chosen checks.

1 answer

1


You can save items marked in localStorage this way:

var ls = localStorage.getItem("box");
if(ls){
   var b = ls.split(",");
   for(var x=0; x<b.length; x++){
      document.getElementById(b[x]).checked = true;
      document.getElementById(b[x]).parentNode.style.display = "none";
      document.querySelector("[data-id='"+b[x]+"']").parentNode.parentNode.style.display = "block";
   }
   var checados = b;
}else{
   var checados = [];
}

var boxes = document.querySelectorAll("#biblio div [type='checkbox']");
for(var x=0; x<boxes.length; x++){
   boxes[x].onchange = function(){
      var idx = checados.indexOf(this.id);
      if(this.checked && !~idx){
         checados.push(this.id);
         document.getElementById(this.id).parentNode.style.display = "none";
         document.querySelector("[data-id='"+this.id+"']").parentNode.parentNode.style.display = "block";
      }else{
         checados.splice(idx, 1);
      }
      localStorage.setItem("box", checados);
   }
}

When reloading the page, checkboxes will still be marked.

Remove the data-id of checkboxes that are not unnecessary since the id has the same value.

  • Just explain to me, please, what these lines you add are running, I don’t think I understand // Document.querySelector("[data-id='"+this.id+"']").parentNode.parentNode.style.display = "block";

  • document.querySelector("[data-id='"+this.id+"']").parentNode.parentNode.style.display = "block" selects the grandfather of the element that has the data-id equal to the id and arrow display block... the parentNode selects the father, if I put 2x, selects the grandfather.

  • Dvd, could you ask me another question? I noticed that the page loads from this line of code var boxes = Document.querySelectorAll("#abas div [type='checkbox']"); so I tried to make that when the page is reloaded it takes the checks marked, that are saved in localStorage compares if there is an image with the same data-id, if it is shows on the screen only those images and hides the others that are not marked. For example I have the pictures 1 2 3 and the checks 1 2 3, if I choose the checks 1 and 2, when I open the page again I would like to appear images 1 and 2.

  • boxes[x]. onchange = Function(){ var idx = checked.indexof(this.id); if(this.checked && !~idx){ checked.push(this.id); }Else{ checked.splice(idx, 1); var img = Document.getElementsByName("icons"); if(this.id == img[x].dataset.id){// compare if the id of the marked checkbox is equal to the image, if it is Document.getElementById("zoom"+x).style.display = 'inline-block'; // shows picture }Else{ Document.getElementById("zoom"+x).style.display = 'None'; // shows picture } }

  • I did it in the answer, no?

  • no, it is disabling the check when I uncheck it, and when reload appears all

  • But the images no longer carry hidden? In this passage document.querySelector("[data-id='"+b[x]+"']").parentNode.parentNode.style.display = "block"; I show only those in the LS.

  • here didn’t work... :/

  • You removed the data-id from these inputs? <input type="checkbox" id="consultar-acervo" data-id="consultar-acervo" name="toggle">

  • No, just add the code in my js file

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.