Search code examples
javascriptjqueryfullcalendarweb-storage

checkbox value from webstorage performing function


I have multiple checkboxes which when clicked, add an eventSource to my jquery fullcalendar. When I refresh the page, I can retrieve the checkbox values from storage but the event sources are not added. I have to uncheck and then recheck the checkbox.

Here is the function clicking on an indivual checkbox performs.

$("#checkbox1").change(function() {
    if (this.checked) {
        $('#calendar').fullCalendar('addEventSource', 'EventListRed.php');
    } else {
        $('#calendar').fullCalendar('removeEventSource', 'EventListRed.php');
    }
});

and here is how I using web storage to keep the checkbox values

$(document).ready(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);
        box.checked = oldVal === "true" ? true : false;
        box.addEventListener("change", function() {
            localStorage.setItem(storageId, this.checked);
        });
    }
});

EDIT:

I have added JSFiddle demo as requested. As you can see the checkbox value is saved, but my events aren't loaded from EventsListRed.php.

Please Note, I am unsure how to link the .php file in the jsfiddle.

I think my issue is I marking the checkbox as checked but its not triggering the change function.


Solution

  • You need to call .fullCalendar( 'refetchEvents' ) before you check that box is checked.

    Please see official docs for refetchEvents

      function setupBox(box) {
        var storageId = box.getAttribute("store");
        var oldVal = localStorage.getItem(storageId);
        $(box).on("change", function() {
          localStorage.setItem(storageId, this.checked);
        });
        box.checked = oldVal === "true" ? true : false;
        $('#calendar').fullCalendar( 'refetchEvents' ); 
        if (box.checked) {   
          $(box).trigger('change');
    
        }
    
      }