initiate a page refresh upon selecting a particular checkbox

So I've got this code that saves around 30 checkbox selections to local storage, which is working fine. Then there's this separate checkbox below, when checked it automatically reloads the page:

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

And here's the code to trigger the page reload:

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

In addition, this is the code snippet where the checkboxes are saved to local storage, and where I need to insert the above reload trigger:

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);

      // Need to add the trigger page reload code here

   });
}

I'm struggling with figuring out how and where to place the code for triggering page reload in the existing script mentioned above. Any assistance would be greatly appreciated!

Answer №1

If you want to handle checkbox changes, you can utilize the ".change" trigger in the following way:

$(document).ready(function() {
   function handleCheckboxChange() {
      var checkedValues = $('.box').map(function() {
         return this.checked;
      }).get();
      localStorage.setItem("checked", JSON.stringify(checkedValues));
   }
   
   var storedCheckedValues = JSON.parse(localStorage.getItem('checked')) || [];
   storedCheckedValues.forEach(function(value, index) {
      $('.box').eq(index).prop('checked', value);
   });
   
   $(".box").click(handleCheckboxChange);

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

Answer №2

Figured it out on my own

window.onload = function() {
   function handleBoxClick() {
      var checkboxStatus = $('.box').map(function() {
         return this.checked;
      }).get();
      localStorage.setItem("checked", JSON.stringify(checkboxStatus));
      if ($('#autoload').is(':checked')) {
         location.reload()
      };
   }
   $(document).ready(function() {
      var checkboxStatus = JSON.parse(localStorage.getItem('checked')) || [];
      checkboxStatus.forEach(function(checked, i) {
         $('.box').eq(i).prop('checked', checked);
      });
      $(".box").click(handleBoxClick);
   });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The custom attribute in jQuery does not seem to be functioning properly when used with the

I am currently working with a select type that includes custom attributes in the option tags. While I am able to retrieve the value, I am experiencing difficulty accessing the value of the custom attribute. Check out this Jsfiddle for reference: JSFIDDLE ...

Is there a way to transfer JavaScript data to PHP?

<div> <p>This is a sample HTML code with JavaScript for tallying radio button values and passing them to PHP via email.</p> </div> If you need help converting JavaScript data to PHP and sending it via email, there are v ...

Having trouble getting a button's OnClick event to work with Bootstrap on iOS devices

Here is an example of the issue I'm experiencing: http://jsfiddle.net/d01sm5gL/2/ The onclick event functions correctly on desktop browsers, however when using iOS8, the event does not trigger. I have tried calling the function manually through the d ...

passing a javascript variable to html

I am facing an issue with two files, filter.html and filter.js. The file filter.html contains a div with the id "test", while the file filter.js has a variable named "finishedHTML." My objective is to inject the content of "finishedHTML" into the test div ...

What is the best way to update $state in AngularJs when the user makes changes to the controller?

I am currently working on Angular UI Router and I want to refresh the current state by reloading it and rerunning all controllers for that state. Is there a way to reload the state with new data using $state.reload() and $stateParams? Here is an example ...

Enable the click functionality for a disabled MI TextField

I'm utilizing a disabled TextField in my project and updating it using React Hooks useState to modify the value property of the TextField. const [employee , setEmployee] = React.useState('') <TextField fullWidth ...

What is the best way to save data from a jQuery plugin to a database using ASP .NET MVC?

I have a jQuery plugin called "Slider" that displays the current price of an item. I would like to enhance it by allowing users to change prices using the jQuery slider and update them in the database. Here is the model: public class Item { public in ...

The Express GET route does not support parameters or additional paths

I am facing an issue with making a fetch request when trying to add additional path or parameters... Here is what I want to achieve: const fetchOwnerCardList = () => { fetch("http://localhost:5000/api/card/ownerCards", { method: "GET", header ...

Activate response upon verifying website link

I am adding functionality to my HTML page where I want certain sections to be visible when the user clicks on a link. Initially, these sections are hidden using the CSS property display: none;. My aim is to make these sections visible when the user clicks ...

Reactivating a React hook following the execution of a function or within a function in ReactJS

A new react hooks function has been created to retrieve data from an API and display it on the page: function useJobs () { const [jobs, setJobs] = React.useState([]) const [locations, setLocations] = React.useState({}) const [departments, setDepartm ...

What would be a colloquial method to retrieve the ultimate result from the iterator function?

I've got a rather complex function that describes an iterative process. It goes something like this (I have lots of code not relevant to the question): function* functionName( config: Config, poolSize: number ): Generator<[State, Step], boo ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...

Monitoring of access controls on Safari during uploads to S3

Safari 10.1.2 Encountering an issue intermittently while attempting to upload PDF files to S3 using a signed request with the Node aws-sdk. Despite working smoothly 90% of the time, have been pulling my hair out trying to resolve this problem. Could it be ...

Add buttons to images to provide further explanations

While browsing the Excel Learn website, I came across a picture that displayed buttons explaining various functions in Excel. By clicking on the picture, a menu would open up to further explain the corresponding button. If you want to see this in action, ...

Ways to access the props value within the lifecycle hooks of Vue JS

Is there a way to retrieve the value of props using lifecycle hooks such as mounted or updated, and then store that value in my v-model with additional text? I've been struggling to achieve this. I attempted using :value on the input element with bot ...

I am seeking assistance with generating a printed list from the database

Struggling for two full days to successfully print a simple list from the database. Take a look at the current state of the code: function CategoriesTable() { const [isLoading, setLoading] = useState(true); let item_list = []; let print_list; useEffect(( ...

Interpreting an undefined HTTP GET request within a Node.js server

I am encountering an issue within my Node.js application. When I send an http get request through an ajax call on the client-side, the server-side does not recognize the request data and returns an "undefined" error message. This problem is puzzling to me ...

Is the neglected property being discarded?

First things first, let's talk about my class: class FavoriteFooBar { ... isPreferred: boolean = false; constructor() { this.isPreferred = false; } } Using a utility library called Uniquer, I arrange a list of FavoriteFooBar instances to pr ...

I created a thorough duplicate that successfully addressed an issue with a table

Currently, I am facing an issue with the material-table library as it automatically adds a new element called tableData to my object when I update it using Patch in my code and API. To resolve this problem, I tried implementing both a conventional and cust ...

Hide preloader in AngularJS once repeater has completed execution

Is there a way to hide a preloader div only after all data has finished loading in an ng-repeat loop? Check out this interactive example on Plunker: http://plnkr.co/edit/ilgOZzIy2axSi5Iy85C7?p=preview Here is the HTML code: <div ng-co ...