saving checkbox state on reload

11,895

Purely in JavaScript supporting localStorage if available, otherwise using document.cookie.

function getStorage(key_prefix) {
    // this function will return us an object with a "set" and "get" method
    // using either localStorage if available, or defaulting to document.cookie
    if (window.localStorage) {
      // use localStorage:
      return {
        set: function(id, data) {
          localStorage.setItem(key_prefix+id, data);
        },
        get: function(id) {
          return localStorage.getItem(key_prefix+id);
        }
      };
    } else {
      // use document.cookie:
      return {
         set: function(id, data) {
           document.cookie = key_prefix+id+'='+encodeURIComponent(data);
         },
         get: function(id, data) {
           var cookies = document.cookie, parsed = {};
           cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
              parsed[key] = decodeURIComponent(value);
           });
           return parsed[key_prefix+id];
         }
       };
     }
  }

jQuery(function($) {
  // a key prefix is used for the cookie/storage
  var storedData = getStorage('com_mysite_checkboxes_'); 

  $('div.check input:checkbox').bind('change',function(){
    $('#'+this.id+'txt').toggle($(this).is(':checked'));
    // save the data on change
    storedData.set(this.id, $(this).is(':checked')?'checked':'not');
  }).each(function() {
    // on load, set the value to what we read from storage:
    var val = storedData.get(this.id);
    if (val == 'checked') $(this).attr('checked', 'checked');
    if (val == 'not') $(this).removeAttr('checked');
    if (val) $(this).trigger('change');
  });

});

jsFiddle demo available -- Click some checkboxes, then "Run" the script again!

Share:
11,895

Related videos on Youtube

input
Author by

input

Seeker of knowledge

Updated on April 28, 2022

Comments

  • input
    input about 2 years

    how do i save checkbox state through sessions? i'm using this jquery code to toggle the options:

    $('div.check input:checkbox').bind('change',function(){
        $('#'+this.id+'txt').toggle($(this).is(':checked'));
    });
    

    but when i reload, the checkboxes are back to their default state. i know i'd have to use sessions, but how do i make the checkbox state persist using sessions in php?

    html:

    <div class="check">
    <p><input type="checkbox" value="Name" id="name" checked /> <label for="name">Name</label></p>  
    <p><input type="checkbox" value="Reference " id="reference" checked /> <label for="reference">Reference</label></p>
        </div>
    
        <div id="nametxt"> Show Name TEXT </div>
        <div id="reftxt"> Show Ref TEXT </div>
    
    • MrWhite
      MrWhite almost 14 years
      @fusion If there is no actual form (being submitted) then this is purely a JavaScript (JQuery) and Cookie question, not PHP or (PHP) Sessions. You will need to use Cookies to maintain state.
  • input
    input almost 14 years
    somehow doesn't work. also i want the default value to be checked, so that the text is shown. but with this code, it shows the code even if the code is unchecked [default] on pageload.
  • Sadat
    Sadat almost 14 years
    can you show your php script plz? are you submitting input through form or JQuery? how? please make it clear.
  • input
    input almost 14 years
    thank you! the demo works wonderfully, and in my project the checkbox state persists, but the corresponding data still displays on pageload, even if the checkbox is unchecked.
  • gnarf
    gnarf almost 14 years
    @fusion - might be something else entirely in a different section of code, can you post a link to the actual page, I can try to firebug it for you.
  • input
    input almost 14 years
    @gnarf, thanks, but the project is not yet online. i tried to firebug it too, it doesn't throw any error as such. the only line in the above code that i changed was this $('#ab_'+this.id).toggle($(this).is(':checked')); . could it be because of this id change?
  • gnarf
    gnarf almost 14 years
    put a breakpoint on that line / the trigger('change'); line and see if it's being run
  • input
    input almost 14 years
    did that, it executes that line. funny thing is that when i put the breakpoint and executed it, it works as it should . .but without the breakpoint, it doesn't -ie, it displays the text if the checkbox is unchecked.
  • bessarabov
    bessarabov about 13 years
    And what is the best way to remove data about checkbox statuses from storage?