使用localStorage保存复选框值

时间:2016-12-02 11:24:24

标签: javascript html checkbox local-storage

我有一个显示/隐藏div,它被一个复选框状态切换,虽然它工作正常我想让localStorage保存复选框状态,但我不知道如何实现本地存储部分的代码以及放置它的位置。任何帮助都感激不尽。

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

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

4 个答案:

答案 0 :(得分:1)

试试这个:http://jsfiddle.net/sQuEy/4/

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

答案 1 :(得分:0)

检查一下:

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")
    }
  });
});

答案 2 :(得分:0)

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)
  });
});

答案 3 :(得分:0)

我必须在本地存储中保存checkbox的值,这可能会指导您将数据存储在本地存储中。 我做了一个复选框和一个按钮。单击“保存”按钮时,将调用一个函数,该函数获取复选框的id并将其与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;
相关问题