Home > OS >  How to edit this jQuery to also save its changes to localStorage?
How to edit this jQuery to also save its changes to localStorage?

Time:12-20

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 ><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.

CodePudding user response:

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 >
  <label><input type="checkbox" id="option1">Check me</label>
</div>

CodePudding user response:

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

CodePudding user response:

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))
   }) 
})
  • Related