Skip to content Skip to sidebar Skip to footer

Use Localstorage To Save A Checkbox Value

I have a show / hide div which is toggled by a checkbox state, although it works fine I would like to have localStorage save the checkbox state, but I don't know how to implement t

Solution 1:

Try this: http://jsfiddle.net/sQuEy/4/

checkboxes[i].checked = localStorage.getItem(checkboxes[i].value) === 'true' ? true:false;

Solution 2:

I had to save the value of checkbox in local storage, maybe that would guide you a bit for storing data in local storage. I made a checkbox and a button. On clicking the " save" button, a function is called which gets the id of checkbox and stores it with localStorage.setItem().

   <input type="checkbox" id="cb1">checkbox</input>
   <buttontype="button"onClick="save()">save</button>functionsave() {    
   var checkbox = document.getElementById("cb1");
   localStorage.setItem("cb1", checkbox.checked);   
   }

  //for loadingvar checked = JSON.parse(localStorage.getItem("cb1"));
  document.getElementById("cb1").checked = checked;

Solution 3:

check this:

LocalStorage

$(document).ready(function() {
  $('#checkbox1').change(function() {
    $('#div1').toggle();
    if (typeof(Storage) !== "undefined") {
      localStorage.setItem("CheckboxValue", $('#checkbox1').is(":checked"));
    } else {
      console.log("No Support for localstorage")
    }
  });
});

Solution 4:

jsfiddle

jQuery(function($) { // Shorter document ready & namespace safer// initiate the statevar checked = localStorage.getItem('checkbox1')
  if (checked) {
    $('#div1').hide()
    $('#checkbox1').prop('checked', true)
  }

  // Toggle the visibility
  $('#checkbox1').change(function() {
    $('#div1').toggle();
    this.checked 
      ? localStorage.setItem(this.id, true)
      : localStorage.removeItem(this.id)
  });
});

Post a Comment for "Use Localstorage To Save A Checkbox Value"