1

This jQuery works great to change the background color of all my divs with the same class (userNumber1), when I check its checkbox, but I need it to also save these changes to localStorage, in order to be there each new time the page is loaded.

After searching for a week in SO, I've tried several different options I've found, but none works properly. While in most cases I can still change the back ground color, some of them save only the checked checkbox but not the background color, other ones do the opposite, yet the most of them save none of both to localStorage.

As I'm not an expert at all, I really don't know what else to do now.

This my jQuery function:

jQuery(document).ready(function($) {
    $('#option1').on('change', function() {
        if ($(this).is(':checked')) {
            $(".userNumber1").css('background-color', "#a7ddff");
        } else {
            $(".userNumber1").css('background-color', "#ffffff");
        }
    })
})

and this one is my HTML code:

<div class="userNumber1"><input type="checkbox" id="option1"><label for="option1"></label></div>

I'm totally open to any different approach, as long as I can save the new background color and the checked/unchecked checkbox to localStorage.

Thank you in advance for your kind support.

rx65m
  • 105
  • 6

3 Answers3

1

Here is a working version - we cannot test localStorage at Stackoverflow due to the sandbox

https://plungjan.name/SO/lschk/

You need to convert a stored string "true" or "false" to boolean

Script

// assuming a not set localStorage means a not checked checkbox at load time
let un1 = localStorage.getItem("userNumber1")

un1 = un1 === null ? false : un1 === "true"; // convert the string stored to boolean

jQuery(document).ready(function($) {
  const $opt1 = $('#option1');

  const changeColor = () => { // make a reusable function 
    const chk = $opt1.is(':checked');
    localStorage.setItem("userNumber1", chk)
    $(".userNumber1").css({
      "background-color": chk ? "lightblue" : "yellow"
    })
  };
  
  $opt1
    .prop("checked", un1)       // set the value from localStorage
    .on('change', changeColor); // assign the listener
  changeColor(); // trigger the initial
})

CSS

.userNumber1 {
  background-color: yellow;
}

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>


<div class="userNumber1">
  <label><input type="checkbox" id="option1">Check me</label>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

Set a local storage key with your value when the user clicks on an option:

localStorage.setItem('backgroundColor', '#FF00BB');
localStorage.setItem('optionId', 'option1');

Retrieve the value when the page loads. Also check the appropriate checkbox:

$('.userNumber1').css('background-color', localStorage.getItem('backgroundColor'));
$('#'+localStorage.getItem('optionId')).prop('checked', true);

Source: Setting "checked" for a checkbox with jQuery

Euthyphro
  • 84
  • 7
  • @rx65m No problem. The second set of two lines go just inside the jQuery ready function. The first two lines need to run when the user clicks the DOM element. – Euthyphro Dec 20 '21 at 12:19
  • Unfortunately it is not saving the changes. – rx65m Dec 20 '21 at 12:41
  • Press F12 and run these lines in the browser and you can see the item is saved and retrieved: localStorage.setItem('backgroundColor', '#FF00BB'); localStorage.getItem('backgroundColor'); Works in Chrome, Firefox, and Edge. Might not work on the default Windows 95 browser. – Euthyphro Dec 20 '21 at 12:47
-1
jQuery(document).ready(function($) {
const myData = localstorage.getItem('myData') ? JSON.parse(localstorage.getItem('myData')) : {'checked':false,'backgroundColor':'#ffffff'};
$("#option1").attr('checked', myData.checked);
$(".userNumber1").css('background-color', myData.backgroundColor);

$('#option1').on('change', function() {
    myData = {}
    if ($(this).is(':checked')) {
        $(".userNumber1").css('background-color', "#a7ddff");
        myData.checked=true;
        myData.backgroundColor = "#a7ddff";
    } else {
        $(".userNumber1").css('background-color', "#ffffff");
        myData.checked=false;
        myData.backgroundColor = "#ffffff";
    }
   localstorage.setItem('myData',JSON.stringify(myData))
   }) 
})
abhishek sahu
  • 648
  • 4
  • 8