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

Asked

Viewed 1,370 times

1

I’m trying to keep the checkbox selected even after refreshing 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 parameter an id of each checkbox I have with an event onclick() and record them in localStorage, I do not know if this is the best way to solve my problem however, it is not working because it is giving error with the global variable "item" always looks like null.

I’m wearing a foreach to check in asp.net mvc.

Basically I just need these selected checkboxes to remain selected after a page re-load.

2 answers

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 a "id" at the event onclick()... you can simply pass the scope of the object in question:

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

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

No need to declare a function ("load") if the only goal is to call it only once when the page loads you can simply make a function "self-executable":

;(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 must go through all the "keys" of localStorage and test them against a single RegExp... this taking into account that all your "checkbox’s" 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: Mozila Docs

  • Friend, it worked, however, only when I put the script inside my loop, because @item.id only exists inside the foreach, which is like this: @foreach (var item in Model){<td>dados</td>&#xA;<td><input id="@item.Id.@idcheck" type="checkbox" onclick="save(this)"></td>} I put an idcheck variable outside the loop, then incremented each item inside the loop and put as key of the localstorage, it worked, but I only managed to put all the script inside the loop. would have some way of doing that by catching the item id. out of the loop and passing to the function?

0


A suggestion is to create only 1 localStorage (instead of creating 1 for each checkbox) and go adding/deleting to id of checkbox clicked. By marking the checkbox, your id is added to the value of localStorage, when clearing, the id is excluded.

For this I created Event handlers to capture the click checkbox instead of calling a function by onclick.

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>
  • Thanks buddy, that’s what I needed, it worked perfectly. I just made a change I created a variable to increment as a key inside the loop:it was like this //c#&#xA; @{ string prefix = "s_item" + idcheck;}&#xA;//html&#xA;<input id="@prefix" type="checkbox">&#xA;

  • @Yes, I’m only going out for 3:00

  • @Leocaracciolo Qual?

  • @Leocaracciolo I went there

Browser other questions tagged

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