【问题标题】:Javascript Save Multiple Checkboxes with LocalStorageJavascript 使用 LocalStorage 保存多个复选框
【发布时间】:2016-10-03 21:03:36
【问题描述】:

我正在尝试使用 localstorage 保存复选框,这样当我刷新浏览器时,选中的复选框会一直存在,直到我单击删除按钮。

这是我迄今为止尝试过的:

function save(){
var checkbox = document.getElementById('ch1');
localStorage.setItem('ch1', checkbox.checked);
}

function load(){    
var checked = JSON.parse(localStorage.getItem('ch1'));
document.getElementById("ch1").checked = checked;
}

function reload(){
location.reload();
localStorage.clear()
}

load();

<body onload="load()">
<input type="button" id="ReserveerButton1" value="save" onclick="save()"/>
<input type="button" id="Wisbutton1" value="delete" onclick="reload()"/>
<input type="checkbox" id="ch1"></input>

//additional checkboxes
<input type="checkbox" id="ch1"></input>
<input type="checkbox" id="ch1"></input>
<input type="checkbox" id="ch1"></input>

</body>

这成功保存了一个复选框,但我想保存多个复选框。因此我假设我需要在函数 save() 中添加一个循环 ...

function save(){
var checkbox = document.getElementById('ch1');
  for (i = 0; i < checkbox.length; i ++) {
    localStorage.setItem('ch1', checkbox.checked);
  }
}

但是,我对如何通过 load() 调用获取这些检查值有些困惑?

干杯

【问题讨论】:

  • 你不能在同一个页面上使用多个相同的id,使用class

标签: javascript html checkbox local-storage


【解决方案1】:

您不能有多个相同的 ID,它们必须是唯一的。

那么,就这样吧

function save(){
  // Get all checkbox inputs
  var inputs = document.querySelectorAll('input[type="checkbox"]');
  var arrData = [];
  // For each inputs...
  inputs.forEach(function(input){
    // ... save what you want (but 'ID' and 'checked' values are necessary)
    arrData.push({ id: input.id, checked: input.checked });
  });
  // Save in localStorage
  localStorage.setItem('inputs', JSON.stringify(arrData));

  console.log(JSON.stringify(arrData));
  // [
  //   {
  //     'id': 'ch1',
  //     'checked': false  // or true
  //   },
  //   ... and so on
  // ]
}

function load(){
  var inputs = JSON.parse(localStorage.getItem('inputs'));
  // For each inputs...
  inputs.forEach(function(input){
    // Set the 'checked' value
    document.getElementById(input.id).checked = input.checked;
  });
}


<input type="checkbox" id="ch1"></input>
<input type="checkbox" id="ch2"></input>
<!-- And so on -->

【讨论】:

    猜你喜欢
    • 2017-05-05
    • 2017-04-17
    • 1970-01-01
    • 2014-07-31
    • 2017-02-11
    • 2012-10-01
    • 2015-07-25
    • 2018-02-20
    • 1970-01-01
    相关资源
    最近更新 更多