Use localStorage to save a checkbox value

2019-09-11 23:32发布

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 the local storage part of the code and where to place it. Any help gratefully received.

  $(document).ready(function() {
    $('#checkbox1').change(function() {
        $('#div1').toggle();
    });
});

<input type="checkbox" id="checkbox1" value="1" />
<div id="div1">Text to be toggled</div>

4条回答
狗以群分
2楼-- · 2019-09-12 00:18

jsfiddle

jQuery(function($) { // Shorter document ready & namespace safer

  // initiate the state
  var 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)
  });
});
查看更多
forever°为你锁心
3楼-- · 2019-09-12 00:23

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

checkboxes[i].checked = localStorage.getItem(checkboxes[i].value) === 'true' ? true:false;
查看更多
走好不送
4楼-- · 2019-09-12 00:33

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>
   <button type="button" onClick="save()">save</button>
   function save() {    
   var checkbox = document.getElementById("cb1");
   localStorage.setItem("cb1", checkbox.checked);   
   }

  //for loading
   var checked = JSON.parse(localStorage.getItem("cb1"));
  document.getElementById("cb1").checked = checked;
查看更多
仙女界的扛把子
5楼-- · 2019-09-12 00:37

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")
    }
  });
});
查看更多
登录 后发表回答