0

Ok, I have a code which saves 30 or so checkbox selections to local storage which works fine, I also have a separate checkbox (as below) which when checked automatically reloads the page

<input type="checkbox" id="autoload" class="autoload"> Tick this box to automatically update the results as you choose them from the options below

Below is the code I have to trigger the page reload

if ($('#autoload').is(':checked')) {
    location.reload(); 
    }

Below is the code which saves the checkboxes to local storage and where I want to add the trigger reload code above

window.onload = function() {
   function onClickBox() {
      var arr = $('.box').map(function() {
         return this.checked;
      }).get();
      localStorage.setItem("checked", JSON.stringify(arr));
   }
   $(document).ready(function() {
      var arr = JSON.parse(localStorage.getItem('checked')) || [];
      arr.forEach(function(checked, i) {
         $('.box').eq(i).prop('checked', checked);
      });
      $(".box").click(onClickBox);
   });
}

My problem is I do not know where or how to place the trigger page reload code into the code above to make it work. Hope all my babblings make sense, any help really appreciated.

Zuckerberg
  • 1,781
  • 2
  • 10
  • 19
Jase
  • 77
  • 11

2 Answers2

0

You can use ".change" trigger for check box like this:

window.onload = function() {
   function onClickBox() {
      var arr = $('.box').map(function() {
         return this.checked;
      }).get();
      localStorage.setItem("checked", JSON.stringify(arr));
   }
   $(document).ready(function() {
      var arr = JSON.parse(localStorage.getItem('checked')) || [];
      arr.forEach(function(checked, i) {
         $('.box').eq(i).prop('checked', checked);
      });
      $(".box").click(onClickBox);
   });
}

$('#autoload').change(() => {
   if ($('#autoload').is(':checked')) {
      location.reload();
   }
});
Zuckerberg
  • 1,781
  • 2
  • 10
  • 19
Mahdi Ahmadi
  • 441
  • 4
  • 12
0

Sorted it myself

window.onload = function() {
   function onClickBox() {
      var arr = $('.box').map(function() {
         return this.checked;
      }).get();
      localStorage.setItem("checked", JSON.stringify(arr));
      if ($('#autoload').is(':checked')) {
         location.reload()
      };
   }
   $(document).ready(function() {
      var arr = JSON.parse(localStorage.getItem('checked')) || [];
      arr.forEach(function(checked, i) {
         $('.box').eq(i).prop('checked', checked);
      });
      $(".box").click(onClickBox);
   });
}
Zuckerberg
  • 1,781
  • 2
  • 10
  • 19
Jase
  • 77
  • 11