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

Proper technique for handling asynchronous results in a Vue component

Where is the ideal place to wait for a promise result in the Vue component lifecycle? Here's a runnable example: https://codesandbox.io/s/focused-surf-migyw. I generate a Promise in the created() hook and await the result in the async mounted() hook. ...

What could be causing the invalid hooks error to appear in the console?

I'm completely stumped as to why this error is popping up when I try to use mutations with React Query. Any insights or advice would be greatly appreciated. Note: I'm implementing this within a function component in React, so it's puzzling ...

Error: The variable <something> has not been defined

Within my GitHub project, an error stating Uncaught ReferenceError: breakpoints is not defined is appearing in the Chrome console. This issue should be resolved by including breakpoints.min.js, but it seems that webpack is somehow causing interference. I ...

Struggling to concentrate on a text field following navigation in an AngularJS application

My current project involves working with an AngularJS application where I am facing a challenge in setting the cursor or focus on a specific text box when routing to a page. Despite my attempts using various methods such as setFocus() in JavaScript, autofo ...

Identifying the specific filter used in Vue-tables-2

Trying to configure a basic server-side vue-tables-2 with dual filters - one dropdown and the other a search field. The challenge here is identifying which filter was applied within the requestFunction() in order to send a server request. My current strate ...

Darkness prevails even in the presence of light

I'm currently in the process of developing a game engine using ThreeJS, and I have encountered an issue with lighting that I need assistance with. My project involves creating a grid-based RPG where each cell consists of a 10 x 10 floor and possibly ...

What is the best method to update the content of one div with content from another page using AJAX?

Having trouble achieving smoother page loads? My goal is to utilize AJAX to specifically fetch a certain div from another page and then swap out the content of a div on this current page with the response. Below is my JavaScript script that uses AJAX to r ...

Is it possible to update the anchor to direct to the data-url attribute of the page?

In order to make my site's navigation more user-friendly, I want the page to scroll to a specific div when an a tag is clicked. This div should have a data-url attribute that matches the href of the clicked a tag. Essentially, the a tag should not nav ...

Tips for extracting HTML entities from a string without altering the HTML tags

I need assistance with removing HTML tags from a string while preserving html entities like &nbps; & é < etc.. Currently, I am using the following method: stringWithTag = "<i> I want to keep my ->&nbsp;<- element space, bu ...

Alter the value of an input element using JavaScript

There are multiple hidden input fields on the page I'm currently working on: <input a1="2" a2="1" a3="3" name="Value" type="hidden" value="10"> <input a1="4" a2="2" a3="6" name="Value" type="hidden" value="12"> <input a1="6" a2="3" a3 ...

LinkButton not triggering on Master Page when accessed from Second Child Page in ASP.NET

I am currently working on a project in ASP.NET (Framework 4.0) where I have implemented an Asp LinkButton in the Master Page that is linked to two different pages (Home.aspx and service.aspx). The question at hand is: The LinkButton1 functions properly on ...

Is it feasible to arrange <DIV>s based on their dates?

I encountered an issue while working with an ordering function. var $wrapper = $('#list'); $wrapper.find('.blogboxes').sort(function (a, b) { return +b.dataset.date - +a.dataset.date; }) .appendTo( $wrapper ); <script src="ht ...

Chat box custom scrollbar always positioned at the bottom

I have a personalized chat box where I included overflow-y for scrolling functionality. However, every time I input a message in the text box, it displays at the top of the scrollbar window. Is there a way to automatically show the most recent message I ...

Sublime Text 3 for React.js: Unveiling the Syntax Files

Currently, my code editor of choice is Sublime Text 3. I recently wrote a simple "hello world" example in React, but the syntax highlighting appears to be off. I attempted to resolve this issue by installing the Babel plugin, however, the coloring still re ...

What is the process for implementing a title search filter in Vue.js?

Hey there, hoping you're having a good night! I've been trying to set up a bookstore using Vue.js with code retrieved from a Json api. However, I'm encountering some issues with the "computed" property. Here's the code snippet: new Vue ...

Display the data received from the client on the NodeJS server

I have a basic html file that includes the following snippet of javascript: <script type="text/javascript"> $.ajax({ url: 'http://192.168.X.X:8080', data: '{"data": "1"}', dataType: ...

Angular can help you easily convert numbers into a money format

I need assistance in converting a number to Indian currency format. Currently, I have attempted the following: http://plnkr.co/edit/lVJGXyuX0BMvB9QUL5zS?p=preview function formatMoney(credits) { console.log(credits+'credits'); var last ...

Tips for creating a dynamic system to continuously add more HTML tables in PHP

I am working with an HTML table where the data is retrieved from a database. I need to add new rows to enter additional data, but the numbering does not continue from the last number. My question is how can I increase the numbering in the table. Please ref ...

How come the light position is not updating?

I am currently using the three.js library to create an animated cylinder: let renderer, camera, scene, light, cylinder; initialize(); animate(); function initialize() { renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer ...

Tips for locating the .owl-video-frame class using jQuery in Owl Carousel 2

In my carousel, I have multiple videos displayed as follows: <div id="owl4" class="owl-carousel owl-theme"> <div class="owl-item-container video-aspect-16-9" data-aspect="1.7777778"> <a class="owl-video" href ...