How to keep checkbox selected after refresh on page with localstorage JS

1

I'm trying to keep the checkboxes selected even after refresh on the page, this is my progress:

// javascript
var s_item = "";

function save(items) {
    s_item = items;
    var checkbox = document.getElementById(s_item);
    localStorage.setItem(s_item, checkbox.checked);
    return s_item;
}

function load() {
    if (s_item != "") {
        var checked = JSON.parse(localStorage.getItem(s_item));
        document.getElementById(s_item).checked = checked;
    }
}
load();

// html
<input id="@item.Id" type="checkbox"  onclick="save('@item.Id');">

In the checkbox, I am trying to pass as an id parameter of each checkbox I have with a onclick() event and writes them to localStorage , I do not know if this is the best way to solve my problem however, right because it is giving error with the global variable "s_item" is always as null .

I'm using foreach to checkboxes in asp.net mvc .

I basically just need these checked checkboxes to remain selected after a reload on the page.

    
asked by anonymous 14.01.2018 / 17:07

2 answers

0

One suggestion is to create only 1 localStorage (instead of creating 1 for each checkbox ) and go adding / deleting to id of checkbox clicked. When you set checkbox , its id is added to the value of localStorage , unchecking, id is deleted.

For this I created event handlers to capture the click on checkbox instead of calling a function with onclick .

It would look like this:

<input id="s_item1" type="checkbox">
<input id="s_item2" type="checkbox">
<input id="s_item3" type="checkbox">

<script>
document.addEventListener("DOMContentLoaded", function(){

   var checkbox = document.querySelectorAll("input[type='checkbox']");

   for(var item of checkbox){
      item.addEventListener("click", function(){
         localStorage.s_item ? // verifico se existe localStorage
            localStorage.s_item = localStorage.s_item.indexOf(this.id+",") == -1 // verifico de localStorage contém o id
            ? localStorage.s_item+this.id+"," // não existe. Adiciono a id no loaclStorage
            : localStorage.s_item.replace(this.id+",","") : // já existe, apago do localStorage
         localStorage.s_item = this.id+",";  // não existe. Crio com o id do checkbox
      });
   }

   if(localStorage.s_item){ // verifico se existe localStorage
      for(var item of checkbox){ // existe, percorro as checkbox
         item.checked = localStorage.s_item.indexOf(item.id+",") != -1 ? true : false; // marco true nas ids que existem no localStorage
      }
   }
});
</script>
    
14.01.2018 / 21:13
0

The problem is that you are setting values to a global variable that when reloading the page will be "empty" until there is a new iteration with a checkbox.

In addition it is not necessary to pass an "id" in the event onclick() ... you can simply pass the object's scope:

<input id="@item.001" name="001" type="checkbox" onclick="save(this)">

<input id="@item.002" name="002" type="checkbox" onclick="save(this)">

You do not have to declare a function ( "load" ) if you only want to call it once when the page loads you can simply do a "self-executing" function:

;(function() {
    // sua lógica aqui
})();

// ou após o HTML ser carregado sem esperar folhas de estilo, imagens, etc...
document.addEventListener('DOMContentLoaded', function(evt) {
    // sua lógica aqui
}, false);

You should go through all the "keys" of localStorage and test them against a simple RegExp ... this taking into account that all your checkboxes are actually prefixed ( "@ item. ").

You can do this using the function key of API Storage .

// salvar
function save(target) {
    localStorage.setItem(target.id, target.checked)
}    

// função auto-executável
;(function() {
    // percorrer todas as chaves em localStorage
    for (let i = 0; i < localStorage.length; i++) {
        // testar chave
        if ( /@item\./g.test(localStorage.key(i)) ) {
            // buscar entrada (checkbox)
            let checkbox = document.getElementById(localStorage.key(i))
            if ( checkbox ) {
                checkbox.checked = JSON.parse(localStorage.getItem(localStorage.key(i)))
            }
        }
    }
})();

Demo : CODEPEN

Reference : Mozilla Docs

    
14.01.2018 / 19:23