(jQuery) Save checkbox state on click in cookie

前端 未结 4 951
春和景丽
春和景丽 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:45

    You can change ALL your code to just: EDITED to remove part unneeded.

    $(document).ready( function(){
       // read the current/previous setting
        $("input.box[type=checkbox]").each(function() {
            var name = $(this).attr('name');
            if ($.cookie(name) && $.cookie(name) == "true") {
                $(this).prop('checked', $.cookie(name));
            }
        });
       // event management
        $("input.box[type=checkbox]").change(function() {
            var name = $(this).attr("name");
            $.cookie(name, $(this).prop('checked'), {
                path: '/',
                expires: 365
            });
        });
    });
    

    including getting rid of all these:

    $(document).ready( function(){
        remember("[name=1]");
    });
    ...
    

    EDIT: less verbose version:

    $("input.box").each(function() {
        var mycookie = $.cookie($(this).attr('name'));
        if (mycookie && mycookie == "true") {
            $(this).prop('checked', mycookie);
        }
    });
    $("input.box").change(function() {
        $.cookie($(this).attr("name"), $(this).prop('checked'), {
            path: '/',
            expires: 365
        });
    });
    

    working example: http://jsfiddle.net/R73vy/

提交回复
热议问题