(jQuery) Save checkbox state on click in cookie

前端 未结 4 952
春和景丽
春和景丽 2021-02-04 19:26

There are a lot of topics regarding this function, nonetheless I can\'t seem to get it working. I\'ve googled on this specific case and a bunch of links let me here, but strangl

4条回答
  •  孤街浪徒
    2021-02-04 19:52

    If you're just interested in one checkbox AND/OR you don't want to include the jQuery cookie plugin for this, here's two lines of code:

    //on page load set the checkbox to stored value or default to true
    $('#turbo').prop('checked' , ( typeof sessionStorage.turbo !== 'undefined' ) ? (sessionStorage.turbo=='true') : true ); 
    //when checkbox is updated, update stored value
    $('#turbo').change( function() { sessionStorage.turbo = $(this).prop('checked');  }); 
    

    This also doesn't use cookies so saves a couple bytes of bandwidth. Change to localStorage to extend lifetime of saved selection.

提交回复
热议问题