Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Set/Delete Cookie with Checkbox??

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #36144
    Taufik Nurrohman
    Participant

    I have a checkbox and a

    
    

    . I would like if checkbox is checked, the

    
    

    will change and the data will be stored in cookies. I was "WARRGHH!!" with JQuery cookie and totally not understand. Can someone explain how to set cookies properly?
    Thank's for your help.

    Here's my explosive code. Be careful when touching: http://jsfiddle.net/tovic/z59DP/embedded/result/

    #94743
    Mottie
    Member

    Forget about cookies, use local storage :P

    #94826
    Mottie
    Member

    Oh, I thought I remembered simpler examples and an example on how to check if localStorage exists. Try this (demo):

    $(function() {

    // check if localStorage exists, from Modernizr
    try {
    if (!localStorage.getItem) { return false; }
    } catch(e) {}

    if (localStorage["preew"]) {
    $('pre').addClass('light');
    $('input:checkbox').prop('checked', true);
    }

    $('input:checkbox').change(function() {
    if ($(this).is(':checked')) {
    localStorage["preew"] = true;
    $('pre').addClass('light');
    } else {
    localStorage["preew"] = false;
    $('pre').removeClass('light');
    }
    });

    });

    I didn’t want to confuse you, but the checkbox change function can be shortened into this:

    $('input:checkbox').change(function() {
    var chk = $(this).is(':checked');
    localStorage["preew"] = chk;
    $('pre')[ chk ? "addClass" : "removeClass" ]('light');
    });
    #103319
    Taufik Nurrohman
    Participant

    YEAHHH!!! xD

    $("input#togglePre").change(function() {
    if ($(this).is(':checked')) {
    $("body").addClass('prelight');
    createCookie("pre", "prelight", 1000);
    } else {
    $("body").removeClass('prelight');
    eraseCookie("pre", "prelight");
    }
    });

    if (readCookie("pre")) {
    $("body").addClass('prelight');
    $('input#togglePre').attr('checked', 'checked');
    }

    http://jsfiddle.net/tovic/z59DP/5/

Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.