views:

52

answers:

2

I have a list of checkboxes.

If the page is refreshed before the user submits the form, I want the state of the checkboxes (checked or not checked) to be preserved.

Ie: user selects option 1, option 4 and option 5. The page refreshes and option 1, option 4 and option 5 remain checked.

I have looked into serialising then storing a cookie but I just cant wrap my head around it.

Any help would be appreciated.

A: 

You can store data in cookies (you could use jquery.cookies.js) when user select option

$('#select_element').change(function() {
  $.cookies.set('check_box', $(this).val());
});

and when you load page put data in check box

$(document).ready(function() {
  if ((check = $.cookies.get('check_box')) != '') {
     $('#select_element').val(check);
  }
});

But I not test it.

jcubic
Thanks for your suggestion jcubic. I've just tried your code but it doesn't seem to work. I wonder if I'm doing it wrong? I simply created:<script type="text/javascript">$('#porchia').change(function() { $.cookies.set('check_box', $(this).val());});</script><script type="text/javascript">$(document).ready(function() { if ((check = $.cookies.get('check_box')) != '') { $('#porchia').val(check); }});</script>The IDs linked to the checkbox. I checked the checkbox, then hit F5 to refresh the page and the check disappeared.
Rich
Sorry this code only work with options form tags, if you want to use checkboxes use this:$(document).ready(function() { if ($.cookies.get('check_box')) { $('#check_box').attr('checked', 'true'); } else { $('#check_box').removeAttr('checked'); } $('#check_box').click(function() { $.cookies.set('check_box', $(this).attr('checked')); });});and html <input type="checkbox" id="check_box" checked="true">
jcubic
A: 

If all your visitors happen to use modern browsers then you can use sessionStorage.

bennedich
I'd like to know how bennedich.
Rich
`sessionStorage` works like a javascript object that persists between requests for as long as the window remains (or until you delete the data manually). Javascript example: `sessionStorage.varName = 3;`. It works in at least chrome, firefox and safari.
bennedich