Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

287
Vistas
How to edit this jQuery to also save its changes to localStorage?

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.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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>
about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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))
   }) 
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda