简体   繁体   English

使用localStorage保持复选框输入处于选中状态

[英]Keep the checkbox inputs checked using localStorage

I am currently learning localStorage and tried to implement some basic function using checkbox, localStorage . 我目前正在学习localStorage并尝试使用复选框localStorage实现一些基本功能。 Basically what I am trying to implement is whenever the checkbox is checked, I want them are keep checked after page reload. 基本上,我要实现的是每当选中此复选框时,我希望在重新加载页面后保持选中状态。

view: 视图:

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

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

I will very appreciate yours helps and if you don't mind could you please let me know what the problem is? 非常感谢您的帮助,如果您不介意的话,请让我知道问题出在哪里?

You need to store the values on save, getting the ID of each checkbox element in your dom. 您需要在保存时存储值,以获取dom中每个复选框元素的ID。

Then once the page loads back, you have to reiterate the values stored in local storage and then get update the dom 然后,一旦页面重新加载,您必须重申存储在本地存储中的值,然后更新dom

Your code had some unknown variables, hence this example below : 您的代码有一些未知变量,因此下面的示例:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM