简体   繁体   中英

How do you save a Checkbox State in localStorage

I'm designing a web app for Document Managers, and there is a 'settings' page, where the user sees a pair of checkboxes formatted to look like the iphone toggle buttons. they work and all, but whenever the user leaves the website or refreshes the page the state of those buttons is reset back to the default. is there a way to save the state of them using localStorage or do i need to use cookies ? EDIT in the JavaScript file (code shown below) there are two functions, one called saveSettings and the other loadSettings , but if i have to do it all in one function then please tell me. END OF EDIT any help at all would be greatly appreciates. so far i have;

localStorage.CheckboxName = $('#CheckboxName').val();

to save the checkbox to localStorage and;

$('#CheckboxName').val(localStorage.CheckboxName);

but it won't save. Am i doing something wrong?

EDIT

here's the HTML code of the two checkboxes;

<li style = 'color: #FFFFFF;'>Notifications<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'notifications' id = 'notifications' /></span></li>
<li style = 'color: #FFFFFF;'>Preview<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'preview' id = 'preview' checked = "true" /></span></li>

END OF EDIT

Any help would be amazing, thanks in advance x

I'm not sure, but I've always believed that it was like this :

window.localStorage.setItem('CheckboxName', $('#CheckboxName').val());

$('#CheckboxName').val(window.localStorage.getItem('CheckboxName'));

You could try the following

$("#CheckboxName").is(':checked')?'checked':'not' and save the output, seems to be what is suggested here: How to use local storage to retain checkbox states for filtering items

To store an Item just remember that the store only holds strings.

Eg.

var val = $('#CheckboxName').val();
window.localStorage.setItem(key, JSON.stringify(val));

So when you read the value back you need to deserialize the string.

var str = window.localStorage.getItem(key);
var obj = $.parseJSON(str);

Or you could just do string comparison whatever suites your needs better in your case what I would do is store an object of id value pairs in one storage key and deserialize them all to work with proper object

Eg.

var val = {
    CheckboxName1: true,
    CheckboxName2: false,
    CheckboxName3: false, // ect....
};
window.localStorage.setItem(key, JSON.stringify(val));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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