What is the efficient way to toggle localStorage based on checkbox selection using jquery?

I am looking to efficiently manage localStorage using checkboxes. When a checkbox is checked, I want to add the corresponding value to localStorage, and remove it when unchecked.

var selectedModes = new Array();
$('.play_mode').on('click', function() {
  var modeValue = $(this).val();
  if ($(this).is(':checked')) {
    selectedModes.push(modeValue);
    localStorage.setItem('selectedMode', modeValue); //set localstorage

  } else {
    selectedModes.pop();
    localStorage.removeItem('selectedMode', modeValue); //remove localstorage
  }
  console.log('Selected modes: ' + selectedModes + '\n Stored mode: ' + localStorage.getItem('selectedMode'));
})
<label><input type="checkbox" class="play_mode" value="101" />101</label>
<label><input type="checkbox" class="play_mode" value="102" />102</label>
<label><input type="checkbox" class="play_mode" value="103" />103</label>
<label><input type="checkbox" class="play_mode" value="104" />104</label>
<label><input type="checkbox" class="play_mode" value="105" />105</label>

However, the current code only stores one value in the localStorage even with multiple checkboxes checked. I aim for it to maintain an array of values like selectedModes.

Refer to this functional fiddle: https://jsfiddle.net/grus6t25/

Answer №1

When a checkbox is clicked, retrieve the item from local storage and determine if it is an array. If the checkbox is checked and the value is not already in the array, add it. If it is unchecked and present in the array, remove it. Finally, update the entire array in local storage.

$('.play_mode').on('change', function(event) {  
  const $checkbox = $(event.target);
  const value = $checkbox.val();
  
  try {
    let pmode = JSON.parse(localStorage.getItem('plmode'));
    
    if (!Array.isArray(pmode)) {
      pmode = [];
    }
    
    if ($checkbox.is(':checked')) {
      if (!pmode.includes(value)) {
        pmode.push(value);
      }
    } else {
      const index = pmode.indexOf(value);

      if (index > -1) {
        pmode.splice(index, 1);
      }
    }
    
    localStorage.setItem('plmode', JSON.stringify(pmode));
  } catch (error) {
    console.log(error);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label><input type="checkbox" class="play_mode" value="101" />101</label>
<label><input type="checkbox" class="play_mode" value="102" />102</label>
<label><input type="checkbox" class="play_mode" value="103" />103</label>
<label><input type="checkbox" class="play_mode" value="104" />104</label>
<label><input type="checkbox" class="play_mode" value="105" />105</label>

Answer №2

To efficiently store all checkbox values, consider utilizing an array or object within the localStorage feature. Here is a practical example using an array:

const localStorage = {
  // Simulated local storage for demonstration
  setItem: (name, value) => console.log(`You have assigned ${name} with ${value}`)
};

$('.play_mode').on('click', function() {
  const plmode = $.map($(".play_mode"), (item) => {
    return {id: item.value, checked: item.checked};
  });
  localStorage.setItem('plmode', JSON.stringify(plmode));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="checkbox" class="play_mode" value="101" />101</label>
<label><input type="checkbox" class="play_mode" value="102" />102</label>
<label><input type="checkbox" class="play_mode" value="103" />103</label>
<label><input type="checkbox" class="play_mode" value="104" />104</label>
<label><input type="checkbox" class="play_mode" value="105" />105</label>

Answer №3

It is important to note that when removing values from local storage, all values are being removed and not just the current checkbox.

Whether you are checking or unchecking a checkbox, it is necessary to update the entire array in the localStorage().

When unchecking a checkbox, avoid popping from the array as it will remove the last value and not the value of the current checkbox. Instead, locate the current value in the array and remove it accordingly.

var pmode = new Array();
$('.play_mode').on('click', function() {
  var pval = $(this).val();
  if ($(this).is(':checked')) {
    pmode.push(pval);
  } else {
    var index = pmode.indexOf(pval);
    if (index != -1) {
      pmode.splice(index, 1);
    }
  }
  localStorage.setItem('plmode', JSON.stringify(pval));
  console.log('pmode:' + pmode + '\n plmode:' + localStorage.getItem('plmode'));
})
<label><input type="checkbox" class="play_mode" value="101" />101</label>
<label><input type="checkbox" class="play_mode" value="102" />102</label>
<label><input type="checkbox" class="play_mode" value="103" />103</label>
<label><input type="checkbox" class="play_mode" value="104" />104</label>
<label><input type="checkbox" class="play_mode" value="105" />105</label>

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

I'm looking to make my PayPal donate button smaller after noticing that PayPal is making it larger. How can I adjust the size of my customized PayPal

I am seeking your help in resolving an issue with PayPal enlarging my button from 130px x 65px to 300px x 150px. I have checked the button on both a local browser and within the Square Space editor, but the result remains the same. I even attempted to adju ...

The correct method to access this LINK

Link to Image for Removal What is the correct method for calling the "Remove" link? How can I use jQuery to trigger the function when the "Remove" link is clicked inside a Bootstrap modal? Here is my HTML: <table> <tr> <td valign ...

"Unable to Access Account: PHP Login Script Failing to Log Users In

I've encountered a login issue with my website script that I can't seem to figure out. The script is designed to log users in after they input their username and password, but for some reason, even with the correct credentials, authentication fai ...

Jasmine tests for AngularJS directive failed to invoke the link function

I can't figure out why the link function of my directive isn't being called in a Jasmine test. I've created a simple example to illustrate. Here is the code for my directive (TestDirective.js): 'use strict'; angular.module(&ap ...

How to detect and resolve the problem of an empty div tag

I'm trying to determine if a div is empty and add the text "empty" to it if it is. Can anyone help me figure out what I'm doing wrong? Thank you in advance! View my jsFiddle file HTML <div class="staff-row"> <img alt="" src="foo.j ...

The class "slick" in <col class="slick"> does not add any styling or effects

My interpretation of the col element is that it can be used to assign a class to all elements in a column of a table. However, I am experiencing difficulties with this approach. While I am able to apply the class to individual td elements, I am looking for ...

Encountering a "Raphael is undefined" error message when working with Treant.js

I need help creating an organizational flow chart using treant.js. Below is my code snippet, but I'm encountering a 'Raphael is not defined' error that I can't seem to solve. Can someone please assist me with identifying the root cause ...

Looking to deactivate the entire keyboard with JavaScript? Make sure that the start key is not disabled, not even Ctrl

Despite my efforts to disable the entire keyboard using JavaScript, I have encountered some limitations. The Windows Start key and Enter key are not being disabled by my script. <script type='text/javascript'> document.onkeydown = functi ...

Difficulty in transmitting two boolean values using ajax and setTimeout()

I am working on two functions that are supposed to send either 0 or 1 to a PHP page using AJAX. When a key is pressed on the keyboard, the function that sends 1 should start, followed by the second function that sends 0 three seconds later using setTimeout ...

Guide to Utilizing the Import Function in a Vue 3 Template

Working on a Vue 3 project, my setup includes a stuff.ts file with helpful functions that I need to utilize in my template. <script lang="ts"> import { defineComponent, onMounted } from 'vue' import { doSomething } from ' ...

What is the best approach for manipulating live data in localStorage using ReactJS?

I am working on creating a page that dynamically renders data from localStorage in real-time. My goal is to have the UI update instantly when I delete data from localStorage. Currently, my code does not reflect changes in real-time; I have to manually rel ...

The UglifyJsPlugin in Webpack encounters an issue when processing Node modules that contain the "let" keyword

Below is the code snippet from my project which utilizes Vue.js' Webpack official template: .babelrc: "presets": [ "babel-preset-es2015", "babel-preset-stage-2", ] webpack.prod.config.js new webpack.optimize.UglifyJsPlugin({ compress: { ...

What are the best strategies for ensuring this website is fully optimized for all devices

Hi there, I've been struggling to make the header on my website responsive, but it doesn't appear to be functioning properly. Any assistance would be greatly appreciated. <!DOCTYPE html> <html lang="en"> <head> <meta name="v ...

What is the process for calculating the total sum of input values utilizing JavaScript?

My JavaScript skills are not perfect, and I'm struggling to calculate the total sum of values in the amount input boxes without refreshing the page. Can someone assist me with this challenge? Thank you. function Calculat ...

What is the best way to use jQuery to dynamically highlight all instances of a word as the user types, both new and existing?

I am currently developing a user-friendly note-taking tool that automatically highlights specific keywords as the user types, making it easier for them to locate important information later on. I have implemented a keyup() function that monitors a text ar ...

What is the best way to create a button that will trigger a modal window to display a message?

I am looking to create a button that will open a modal window displaying a message. However, when I tried to add a label and viewed the page, the desired window appeared on top of the rest of the content. But unfortunately, clicking the button did not prod ...

Even though I have successfully compiled on Heroku, I am still encountering the dreaded Application Error

Looking for help with a simple express/node application to test Heroku? Check out my app.js: const express = require('express') const app = express() const port = '8080' || process.env.PORT; app.get('/', function (req, res) ...

Dealing with errors using Javascript and Node.js (then/catch)

Suppose I have the following pseudocode in my routes.js file: var pkg = require('random-package'); app.post('/aroute', function(req, res) { pkg.impl_func(data, function (err, result) { myFunction(entity).then(user=>{ ...

Tips on keeping Bootstrap Modals out of your browsing history

Imagine this scenario A visitor lands on Page A, clicks through to Page B, and then engages with a link that triggers a modal (code provided below) <a href="mycontent.html" data-target="#modal_xl" data-toggle="modal" data-backdrop="static">Click me ...

Guide on troubleshooting Node TypeScript in Visual Studio Code when the JavaScript source is stored in a separate directory

When using Visual Studio Code, I am able to debug and step through the TypeScript source code of Main.ts. This is possible as long as the JavaScript and map files are located in the same folder as the TypeScript source. This setup works well in this struc ...