admin管理员组文章数量:1331653
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
<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">
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
<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">
Share
Improve this question
edited Jan 17, 2016 at 8:46
Ibrahim Khan
20.8k7 gold badges45 silver badges56 bronze badges
asked Jan 16, 2016 at 20:23
About LerosAbout Leros
1905 silver badges16 bronze badges
2
- those checkboxes all have the same name ....why? Also you are trying to set them all to same key in storage...need to use array to do that. Each will overwrite the last – charlietfl Commented Jan 16, 2016 at 20:28
- 1 Ok, well I wouldn't have asked the question if I knew how to do it, would I? – About Leros Commented Jan 16, 2016 at 20:39
3 Answers
Reset to default 4Simply 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:
"[{\"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'. 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 :
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:
$("input[name*='favorite']").change(function () {
var name = $(this).attr('name'),
value = $(this).val();
localStorage.setItem(name,value);
console.log(localStorage.getItem(name));
});
Case 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 :
<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
Now the last trick is to convert that array of values into a string, using the awesomeness of the JSON object like this :
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.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 :
var values = localStorage.getItem('favorite').split(',');
Finally that's it
Here is a jsfiddle example
Hope this helps.
本文标签: javascriptHow to save multiple checkbox values to local storageStack Overflow
版权声明:本文标题:javascript - How to save multiple checkbox values to local storage? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742270608a2444233.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论