jeudi 22 septembre 2016

Getting checkbox id out of local storage for with JQuery

I am working on a form that on reload has to save and show the marked checkboxes, i made the code that can save it in to local storage but now i don't know how to get the id's of the checkboxes out of the local storage so they will be checkt again on reloading the page.

Here is a JSFiddle

The code:

// this code saves the marked checkbox in the local storage

$('.required-option').on('click', function() {
  var fav, favs = [];
  $('.required-option').each(function() { // run through each of the checkboxes
    fav = {
      id: $(this).attr('id'),
      value: $(this).prop('checked')
    };
    if (fav.value === true) {
      favs.push(fav.id);
    }
  });
  localStorage.setItem("checkbox", JSON.stringify(favs));
});
<script src="http://ift.tt/1oMJErh"></script>
<input type="checkbox" class="required-option" id="like1" />
<input type="checkbox" class="required-option" id="like2" />
<input type="checkbox" class="required-option" id="like3" />
<input type="checkbox" class="required-option" id="like4" />
<input type="checkbox" class="required-option" id="like5" />
<input type="checkbox" class="required-option" id="like6" />
<input type="checkbox" class="required-option" id="like7" />
<input type="checkbox" class="required-option" id="like8" />
<input type="checkbox" class="required-option" id="like9" />



Aucun commentaire:

Enregistrer un commentaire