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

Instructions for user to upload and play an MP4 file on their PC

For my web project that utilizes node.js, HTML, and JavaScript, I am looking to incorporate a video player element. I want users to have the ability to click a button and play an MP4 file directly on the webpage. How can I achieve this? I currently have s ...

Tips on resolving the flickering issue in dark mode background color on NextJS sites

One problem I am facing is that Next.js does not have access to the client-side localStorage, resulting in HTML being rendered with or without the "dark" class by default. This leads to a scenario where upon page reload, the <html> element momentari ...

Unable to adjust the width of a table column within a horizontally scrollable container

I am struggling to resize the columns of a large table with 20 headers. Despite trying to place the table inside a div with overflow:auto, I still cannot achieve horizontal scrolling or make the div expand when resizing the columns. A sample code snippet ...

What is the jQuery alternative for the classList property in vanilla JavaScript?

Currently, I am working on a collaborative project with two acquaintances. One of the requirements is to stick to either vanilla JavaScript selectors like document.getElementById("thisDiv"); or jQuery selectors such as $("#thisDiv"); to maintain consis ...

Troubleshooting EasyTabs: Localhost Issue with Ajax Tab Configurations

I've implemented EasyTabs for organizing my tabs on a webpage. I decided to use ajax-tabs functionality in order to fetch content from other pages when users click on the navigation menu buttons. However, I've encountered an issue where the conte ...

Semi-Transparent Photo Slideshow

Currently, I am in the process of developing a Pokedex-like feature for a project that I am working on. The functionality is working as expected, but there is one particular feature that I would like to implement. My goal is to display only certain element ...

Is there a way to format this into four columns within a single row while ensuring it is responsive?

I am working on a layout with a Grid and Card, aiming to have 4 columns in one row. However, the 4th column ends up in the 2nd row instead, as shown below: My goal is to align all 4 columns in a single row. Additionally, when viewed on a small screen, th ...

Is there a way to iterate through objects and add new properties to them?

I am trying to achieve the following object: let newPost = { title: "Post 1", Content: "New content" } with the code below: let newPost = {}; let postData = $(".post-data").each (function(index) { newPost.title = $ ...

Chrome is experiencing a delay in closing the Select Option dropdown menu

On my webpage, I have two select option buttons placed on different tabs. Whenever one button is changed, I want to update the value of the other button and assign it to a specific element like a span in the example code provided. While everything works sm ...

Steps for importing a JavaScript file from Landkit into a Vue project

Currently, I am working on an interesting project and utilizing Vue with Landkit Bootstrap. However, I am encountering issues with the JavaScript behavior of the Landkit component. I usually import the following links in my index.html file, but in the new ...

Reveal and conceal using CSS animations

I am working on adding animation effects to show and hide HTML elements triggered by a button click. The button toggles a "hide" class to display or hide the element. Check out my code snippet: const toggleButton = document.querySelector('button ...

Inquiring about the Model component within the MVC architecture in a web application created with NodeJs and integrated with

As a beginner in NodeJs, I am venturing into creating web applications using the express framework and MySQL. Understanding that in MVC architecture, views are represented by *.ejs files, controllers handle logic, and models interact with the database. Ho ...

The dichotomy between public and private methods within a Vue.js component

Within a component, I have two functions defined. One is foo(), which is defined within <script>, and the other is fooExported(), which is defined in the body of export default {}. My understanding is that functions inside export default {} can be a ...

An issue in D3.js where the chart bars are not properly synced with the x-axis labels

Currently delving into the world of d3.js for the first time. In our project, we needed to adjust the width of each bar from .attr('width', xScale.rangeBand()) line 46 to .attr('width', '10') line 50 After making this cha ...

Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

<td>{{suite.testSuiteAttributes && suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd' }} </td> I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an ...

using JQuery, add a class on click event or on page load

Solved It! After encountering a problem created by some sloppy moves on my part, I managed to solve it. However, another issue arose: adding the class current to li with data-tab="tab-1 upon page load. $('ul.tabs li').click(function(){ ...

Listening for time events with JQuery and controlling start/stop operations

I recently developed a jQuery plugin. var timer = $.timer(function() { refreshDashboard(); }); timer.set({ time : 10000, autostart : true }); The plugin triggers the refreshDashboard(); function every 10 seconds. Now, I need to halt the timer for ...

Creating a sticky header for a MatTable in Angular with horizontal scrolling

Having an issue with merging Sticky Column and horizontal scrolling. Check out this example (it's in Angular 8 but I'm using Angular 10). Link to Example The base example has sticky headers, so when you scroll the entire page, the headers stay ...

Remove an item from a complex JSON structure based on the specified name. The function will then return the

Hey there, I'm just starting out with react native and I have an array of objects. My goal is to remove an inner object from this JSON data. [ { Key: 1, exchnageArr: [ { name: ”FX” }, { name: ”MK” ...

What is the best way to generate a specified number of rows with 3 columns in each row using jquery?

After spending 3 hours trying to create a boostrap 'card' with 3 identical cards per row, I unfortunately failed. Here is the code I attempted: $.getJSON("./listings.php", function(e) { $.each(e, function(i, e){ if (e.id != ...