Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

284
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda