javascript - How to save multiple checkbox values to local storage? -
i'm trying save multiple check boxes in local storage, see code below , idea.
what have tried far:
$(function () { var data = localstorage.getitem("favorite"); if (data !== null) { $("input[name='favorites']").attr("checked", "checked"); } }); $("input[name='favorites']").click(function () { if ($(this).is(":checked")) { localstorage.setitem("favorite", $(this).val()); } else { localstorage.removeitem("favorite"); } });
html
<input type="checkbox" class="fachkrnd" name="favorite1" id="like"> <input type="checkbox" class="fachkrnd" name="favorite2" id="like1"> <input type="checkbox" class="fachkrnd" name="favorite3" id="like2">
simply serialize them.
$('.fachkrnd').on('click', function() { var fav, favs = []; $('.fachkrnd').each(function() { // run through each of checkboxes fav = {id: $(this).attr('id'), value: $(this).prop('checked')}; favs.push(fav); } localstorage.setitem("favorites", json.stringify(favs)); });
they saved in json so:
"[{\"id\": \"like\", \"value\": true},{\"id\": \"like2\", \"value\": true},{\"id\": \"like3\", \"value\": true}]"
which can later load:
var favorites = json.parse(localstorage.getitem('favorites'));
and loop through reassign:
for (var i=0; i<favorites.length; i++) { $('#' + favorites[i].id ).prop('checked', favorites[i].value); }
here's working fiddle. can check box, , refresh see values loaded.
Comments
Post a Comment