简体   繁体   English

如何将多个复选框值保存到本地存储?

[英]How to save multiple checkbox values to local storage?

I'm trying to save multiple check boxes in local storage, see the code below and you get the idea. 我正在尝试在本地存储中保存多个复选框,请参见下面的代码,您就会明白。

What I have tried so far: 到目前为止我尝试过的是:

$(function () {
var data = localStorage.getItem("favorite");

if (data !== null) {
    $("input[name='favorites']").attr("checked", "checked");
}
});
$("input[name='favorites']").click(function () {

if ($(this).is(":checked")) {
    localStorage.setItem("favorite", $(this).val());
} else {
    localStorage.removeItem("favorite");
}
});

Html HTML

<input type="checkbox" class="faChkRnd" name="favorite1" id="like">
<input type="checkbox" class="faChkRnd" name="favorite2" id="like1">
<input type="checkbox" class="faChkRnd" name="favorite3" id="like2">

Simply serialize them. 只需序列化它们。

$('.faChkRnd').on('click', function() {
    var fav, favs = [];
    $('.faChkRnd').each(function() { // run through each of the checkboxes
        fav = {id: $(this).attr('id'), value: $(this).prop('checked')};
        favs.push(fav);
    }
    localStorage.setItem("favorites", JSON.stringify(favs));
});

They will be saved in a JSON like so: 它们将以如下方式保存在JSON中:

"[{\"id\": \"like\", \"value\": true},{\"id\": \"like2\", \"value\": true},{\"id\": \"like3\", \"value\": true}]"

Which you can later load: 您以后可以加载:

var favorites = JSON.parse(localStorage.getItem('favorites'));

And loop through to reassign: 并循环进行重新分配:

for (var i=0; i<favorites.length; i++) {
    $('#' + favorites[i].id ).prop('checked', favorites[i].value);
}

Here's a working fiddle . 这是工作中的小提琴 You can check a box, and refresh to see the values loaded. 您可以选中一个框,然后刷新以查看加载的值。

That would be less operations with arrays you can do without 'IF'. 如果没有“ IF”,则可以对数组进行较少的操作。 With every click simply re-save all the selected checkboxes. 只需单击一下,即可重新保存所有选定的复选框。

$("input[name='favorites']").click(function () {
   var c = [];
   $(this).is(":checked").each(function (i) {
       c.push( $(this).attr('id') );
       localStorage.setItem("favorite", JSON.stringify(c));
   });         
});

To get the value: 获取值:

var fav = JSON.parse(localStorage.getItem("favorite"));

We have two cases here 这里有两种情况

Case 1 : 情况1 :

Want to store checkbox values for elements with different names here is an example for this scenario : 想要存储具有不同名称的元素的复选框值,这里是这种情况的示例:

<input type="checkbox" class="faChkRnd" name="favorite1" id="like" value="val1">
<input type="checkbox" class="faChkRnd" name="favorite2" id="like1" value="val2">
<input type="checkbox" class="faChkRnd" name="favorite3" id="like2" value="val3">

here all the checkboxs have a name that starts with favorite , so we can reference them using this information and then store each checkbox name with its appropriate value as a separate item in the localStorage Here is the JS code: 在这里,所有复选框的名称都以“ favorite开头,因此我们可以使用此信息引用它们,然后将每个复选框名称及其适当的值作为单独的项存储在localStorage这是JS代码:

$("input[name*='favorite']").change(function () {
    var name = $(this).attr('name'),
        value = $(this).val();

    localStorage.setItem(name,value);
    console.log(localStorage.getItem(name));        
});

Case 2 : 情况2:

We want to reference multiple checkboxs with the same name . 我们要引用多个具有相同名称的复选框。 First we change the value of the name attribute as it is shown in the following : 首先,我们更改name属性的值,如下所示:

<input type="checkbox" class="faChkRnd" name="favorite" id="like" value="val1">
<input type="checkbox" class="faChkRnd" name="favorite" id="like1" value="val2">
<input type="checkbox" class="faChkRnd" name="favorite" id="like2" value="val3">

Second we get the data like we've done before but the special thing this time is that the eventListener is fired when each element with that name change the checked property, so the value is generated again with the proper value and it is an array that is for sure because we have multiple values 其次,我们像以前一样获得数据,但是这次的特别之处在于,当每个具有该名称的元素更改了checked属性时,将eventListener ,因此将再次使用适当的值生成该值,并且该数组是一个是肯定的,因为我们有多个值
Now the last trick is to convert that array of values into a string, using the awesomeness of the JSON object like this : 现在,最后一个技巧是使用JSON对象的出色功能将值数组转换为字符串:

var valueStringified = JSON.stringify(value);

OR simple enough use your own delimiter to join the array values, for example : 使用您自己的定界符将数组值联接起来就足够简单了,例如:

var valueStringified  = value.join(',');

Now store it to your localStorage as one string 现在将其作为一个字符串存储到您的localStorage中

localStorage.setItem('favorite',valueStringified);

And when you want to retrieve the value of the element, it is very simple just get the item name localStorage.getItem('favorite') and then split it to get an array using the previous delimiter, something like that : 而且,当您要检索元素的值时,非常简单,只需获取项目名称localStorage.getItem('favorite') ,然后使用先前的分隔符拆分为一个数组即可,如下所示:

var values = localStorage.getItem('favorite').split(',');

Finally that's it 最后就是这样

Here is a jsfiddle example 这是一个jsfiddle示例

Hope this helps. 希望这可以帮助。

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

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