dimanche 4 décembre 2016

Show div on checkbox check and hide it when unchecked (even on load because localstorage)

So the page must show a div if a checkbox is checked and hide it when it is unchecked. But I am using localstorage so it shouldn't hide on load of the page but only when it is unchecked. And if it is possible it should be usable for a lot of checkboxes (37 exactly)

My code so far:

HTML:

<div id="mob1-div" class="row hide one">Mobilisern1</div>
<div id="mob2-div" class="row hide-div">Mobilisern2</div>

<div id="mob1" class="targetDiv">Mobiliseren 1<input type="checkbox" class="checkbox chk" value="one" data-ptag="mob1-div" store="checkbox1"/></div>
<div id="mob2" class="targetDiv">Mobiliseren 2<input type="checkbox" class="checkbox" data-ptag="mob2-div" store="checkbox2"/></div>

Javascript:

$(function() {
    var boxes = document.querySelectorAll("input[type='checkbox']");
    for (var i = 0; i < boxes.length; i++) {
        var box = boxes[i];
        if (box.hasAttribute("store")) {
            setupBox(box);
        }
    }

    function setupBox(box) {
        var storageId = box.getAttribute("store");
        var oldVal    = localStorage.getItem(storageId);
        console.log(oldVal);
        box.checked = oldVal === "true" ? true : false;

        box.addEventListener("change", function() {
            localStorage.setItem(storageId, this.checked); 
        });
    }
});
$(function(){
$(".chk").on('change',function(){
var self=$(this);
    var aData= self.attr("value");
    $("."+aData).toggleClass('hide')
});
});

the problem with this code is that if you check the box the div shows but if you reload the page the box is still checked but the div isn't visible anymore.




Aucun commentaire:

Enregistrer un commentaire