Experiencing Difficulty Retaining Checkbox State Using LocalStorage Upon Page Reload

At the moment, I have a script that automatically clicks on a random checkbox whenever the page loads or refreshes. Through localStorage, I can also view the value of the input assigned to the randomly selected checkbox.

However, I'm facing an issue where none of the checkboxes stay checked upon page load or refresh using localStorage and it has left me puzzled right now.

HTML

<div id="all-games">
   <div>
      <h2>Microsoft Xbox</h2>
         <ul id="games" class="no-bullets">
            <img src="./Game Covers/Microsoft/Microsoft Xbox/call of duty 3.png">
            <li class="video-game"><label><input type="checkbox" value="cod-3" onchange="scrollToGame()"/></label>Call of Duty 3</li>

            <!-- Other game checkboxes -->

         </ul>
   </div>
</div>

Javascript

<script>
   const games = document.querySelectorAll(".video-game input[type=checkbox]:not(:checked)"); // select games that are currently not checked
   const checkbox = Math.floor(Math.random() * games.length); // get a random index from 0 to games length
   const scrolledGame = games[checkbox];
   scrolledGame.click(); // click on the checkbox for the randomly selected game
   const gameValue = scrolledGame.value;

   function scrollToGame() { 
      scrolledGame.scrollIntoView({ 
         behavior: "smooth"
      });

   };

   if (scrolledGame.checked) {
      localStorage.setItem('game title', gameValue); // title value of the selected checkbox via localStorage
      scrolledGame.checked = true;
   };

   if (localStorage.getItem('game title') === gameValue) {
      scrolledGame.checked = true;
      console.log(scrolledGame.checked);
   };
</script>

Answer №1

Query: I've struggled to maintain the checked status of checkboxes after a page load or refresh using localStorage

The issue arises from each page refresh resulting in a new checkbox being checked, causing inconvenience. Your approach to saving and retrieving 'game title' is correct. To maintain checkbox states persistently, refrain from altering them upon page refresh. Instead, retrieve 'game title' and check the corresponding checkbox.

Below code snippet ensures the persistence of the last checked checkbox:

<body>
<div id="all-games">
    <div>
       <h2>Microsoft Xbox</h2>
          <ul id="games" class="no-bullets">
             <img src="./Game Covers/Microsoft/Microsoft Xbox/call of duty 3.png">
             <li class="video-game"><label><input type="checkbox" id="cod-3" onchange="save('cod-3')"/></label>Call of Duty 3</li>
             <img src="./Game Covers/Microsoft/Microsoft Xbox/phantasy star online episode i & ii.png">
             <li class="video-game"><label><input type="checkbox" id="phantasy-star-online" onchange="save('phantasy-star-online')"/></label>Phantasy Star Online Episode I</li>
             <img src="./Game Covers/Microsoft/Microsoft Xbox/phantasy star online episode i & ii.png">
             <li class="video-game"><label><input type="checkbox" id="phantasy-star-online-ii" onchange="save('phantasy-star-online-ii')"/></label>Phantasy Star Online Episode II</li>
             <img src="./Game Covers/Microsoft/Microsoft Xbox/shrek.png">
             <li class="video-game"><label><input type="checkbox" id="shrek" onchange="save('shrek')"/></label>Shrek</li>
             <img src="./Game Covers/Microsoft/Microsoft Xbox/soulcaliber ii.png">
             <li class="video-game"><label><input type="checkbox" id="soulcaliber-ii" onchange="save('soulcaliber-ii')"/></label>SoulCalibur II</li>
             <img src="./Game Covers/Microsoft/Microsoft Xbox/spiderman 2.png">
             <li class="video-game"><label><input type="checkbox" id="spiderman-2" onchange="save('spiderman-2')"/></label>Spider-Man 2</li>
             <img src="./Game Covers/Microsoft/Microsoft Xbox/star wars episode iii.png">
             <li class="video-game"><label><input type="checkbox" id="star-wars-episode-iii" onchange="save('star-wars-episode-iii')"/></label>Star Wars Episode III: Revenge of the Sith</li>
          </ul>
    </div>
 </div>

 <script>

    if (localStorage.getItem('game title')) {  
      let game = localStorage.getItem('game title')
      document.querySelector(`input[id=${game}]`).checked = true;
    }

    function save(game) { 
      if (document.querySelector(`input[id=${game}]`).checked === true) {
        localStorage.setItem('game title', game); 
      } else {
        localStorage.setItem('game title', '')
      }
    }
 </script> 

</body>

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 JSON data sent from the primary Electron process is arriving as undefined in the renderer

Currently delving into an Electron project to explore the technology. It's been a captivating and enjoyable experience so far as I work on creating a basic home controller for my IoT devices. However, I've encountered a minor issue. In my main.js ...

What is the reason for Backbone including model details within {model: {model_property: value,...}} when saving a model?

I am currently developing an application using node.js and backbone.js. However, I have encountered an issue where saving a model results in the JSON being nested inside a model dictionary. node = new NodeModel({prop1:"value1", prop2:"value2"}); node.save ...

Troubleshooting ng-repeat in AngularJS: Multi checkbox filter malfunction

My AngularJS app has multiple age range filters implemented, but one of them is not functioning correctly and I can't figure out why. You can view a functional example here. The various filters are defined as follows: .filter('five', func ...

Assigning the Style property to an element using a string that includes HTML tags

My HTML string is populated with elements such as button, li, span, and more. I am looking to add specific styles to buttons based on their class name. For example, if button.btn { some styles } and button.btn-success { some other styles } O ...

Is it possible to incorporate a React app as a component within a static HTML page?

Looking to integrate the react-csv-viewer component into a static HTML page without deploying it on a local server. I've tried following the instructions from the React tutorial, but am struggling with the build process. My goal is simple - to use th ...

Removing zeros from a one-dimensional tensor in TensorFlow.js: A step-by-step guide

If I have a 1D tensor (distinct from an array) with the values [0,2,0,1,-3], my goal is to retrieve only the non-zero values. Using the example provided, I want to receive [2,1,-3] as the output. Is there a way to achieve this in TensorFlow.js? ...

Utilizing JavaScript to trigger a series of click events on a single button in order to

I am working on implementing a click event for a checkbox that will add and remove CSS classes using the "classList.toggle" method. Specifically, I want the checkbox to toggle between adding the "xyz" class on the first click, and then adding the "abc" cla ...

Integrating a footer into the enhanced search tab slider

I'm struggling to create a sticky footer like the one on w3schools. Even though I used the same code in my material UI demo, it's not functioning properly. I tried debugging by changing the position from fixed to absolute, but it still isn&apos ...

Navigating through the website has become quite challenging due to the malfunctioning navigation bar. Instead

I recently completed a website and designed an awesome navigation bar in a separate file. However, when I combined them together, the navigation bar disappeared. The background of my "list" div should be filled in and larger, but it's not working as e ...

Using JavaScript to display dynamic data pulled from Django models

I am currently in the process of designing my own personal blog template, but I have encountered a roadblock when it comes to creating a page that displays previews of all posts. This particular page consists of two columns, #content-column-left and #conte ...

Implementing Asynchronous Custom Validators in Angular 4

I've encountered the following code snippet: HTML: <div [class]="new_workflow_row_class" id="new_workflow_row"> <div class="col-sm-6"> <label class="checkmark-container" i18n>New Workflow <input type="che ...

Ways to extract the initial layer of information from a JSON document

I have a JSON file named movie.json stored externally, and it follows this format: { "action": [ { "id": "1001", "name": "Matrix" }, { "id": "1002", & ...

ChartJS does not function properly when included in a .php file that is loaded using jQuery's .load() method (

I am facing an issue with this plugin not working when I use the jQuery ajax function .load(). Below is the snippet of my PHP code: <script src="../Chart.js"></script> <script type="text/javascript" src="../functions.js"></script> ...

Arranging an Array of Objects in JavaScript by dual criteria

In my JavaScript code, I have an object structured like this: myArray[0] -> 0:"62", 1:8, 2:0, 3:"11" myArray[1] -> 0:"62", 1:8, 2:0, 3:"15" myArray[2] -> 0:"48", 1:8, 2:0, 3:"04" myArray[3] -> 0:"48", 1:8, 2:0, 3:"01" myArray[4] -> 0:"62", ...

Is there a way for me to divide the data in a JSON file and display user tags in place of their IDs?

Looking to create a list admins command for a bot, I'm facing challenges in converting user ids to tags within the command. Take a look at what I have accomplished so far: const { MessageEmbed } = require('discord.js'); const { readFileSync, ...

New Feature in Bootstrap4: Navigation Bar Alignment Shift to the Left

I need help aligning my links to the right side of the page I attempted to use mr-auto but it was not effective <body> <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top mr-auto mt-2 mt-lg-0"> <a class="navbar-brand" hre ...

Each time forEach is called, it increments the previous result by 1

My service returns a response containing the following data: {"id":157336,"results":[ {"id":"53db3c790e0a26189a000d09","iso_639_1":"en","key":"ePbKGoIGAXY","name":"Trailer 3","site":"YouTube","size":1080,"type":"Trailer"}, {"id":"550df44b925141355 ...

Responsive Input Navigation Bar CSS

How can I create a top bar that resembles the design of Google Play? I am struggling to make the input box flexible and fit the window size... The minimum width of Div.search is set to 250px but it's not working. Can someone help? *{ box-sizing: ...

Best Practices for Variable Initialization in Stencil.js

Having just started working with Stencil, I find myself curious about the best practice for initializing variables. In my assessment, there seem to be three potential approaches: 1) @State() private page: Boolean = true; 2) constructor() { this.p ...

Clickable list element with a button on top

Within my web application, there is a list displaying options for the user. Each 'li' element within this list is clickable, allowing the user to navigate to their selected option. Additionally, every 'li' element contains two buttons - ...