使用localStorage选中复选框输入

时间:2018-08-25 14:13:31

标签: javascript local-storage

我目前正在学习localStorage,并尝试使用复选框localStorage 来实现一些基本功能。基本上,我要实现的是每当选中此复选框时,我希望在重新加载页面后保持选中状态。

视图:

 <div>
    <label><input type="checkbox"value="<%=obj.id%>" name="selected" class="select_class"></label>
 </div>

JS

  $("#save_button").click(function(){
    var selecteditems = [];

      if (!$("input[name='selected']:checked").is(":checked")) {
          localStorage.removeItem('chx');
         //if checkboxs are not checked, remove the setItem
        }
      else{
        $("input[name='selected']:checked").each(function(){
        var checked = $(this).val();
        if(checked){
          selecteditems.push(checked);

        localStorage.setItem('chx', JSON.stringify(selecteditems));
        var localcheckdata =JSON.parse(localStorage.getItem('chx'));  
        }

        $.each($("input[name='selected']"), function(){
         localcheckdata.push($(this).val());
       });

非常感谢您的帮助,如果您不介意的话,请让我知道问题出在哪里?

1 个答案:

答案 0 :(得分:0)

您需要在保存时存储值,以获取dom中每个复选框元素的ID。

然后,一旦页面重新加载,您必须重申存储在本地存储中的值,然后更新dom

您的代码中有一些未知变量,因此下面的示例:

var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
    $checkboxes = $("#checkbox-container :checkbox");

// on save button clicked
$("#save_button").click(function(){
  $checkboxes.each(function(){
    checkboxValues[this.id] = this.checked;
  });

    localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));

});


// On page load
$.each(checkboxValues, function(key, value) {
  $("#" + key).prop('checked', value);
});
<div id="checkbox-container">
  <div>
    <label for="option1">Option 1</label>
    <input type="checkbox" id="option1">
  </div>
  <div>
    <label for="option2">Option 2</label>
    <input type="checkbox" id="option2">
  </div>
  <div>
    <label for="option3">Option 3</label>
    <input type="checkbox" id="option3">
  </div>
</div>

相关问题