Skip to content Skip to sidebar Skip to footer

Set Jquery Cookie For Each Checkbox

I have a simple jQuery function that toggles classes based on checkbox states. Here's the code: jQuery: $('input[name$='bg-noise-option']').click(function(){ var targetClass

Solution 1:

This assumes you're using the JQuery Cookie Plugin, since I see you referenced it in your question.

Here you are. Creates and alters a single cookie file upon any checkbox click, storing only those data-at values that correspond to checked boxes.

On page load, it retrieves that JSON string, coverts it back to an object, then loops through, applying a check to the box of any matching attribute.

Code tested and working.

HTML: I added '[]' to your checkboxes to properly group them and removed any default checked boxes.

<divclass="checkbox"><label><inputtype="checkbox"name="bg-noise-option[]"data-at="page-wrap">
        Body <br></label><label><inputtype="checkbox"name="bg-noise-option[]"data-at="btn">
        Elements <br></label><label><inputtype="checkbox"name="bg-noise-option[]"data-at="header, .navbar">
        Top Header <br></label><label><inputtype="checkbox"name="bg-noise-option[]"data-at="page-header-wrap">
        Page Header <br></label><label><inputtype="checkbox"name="bg-noise-option[]"data-at="site-footer">
        Footer <br></label></div>

JQuery: using $.cookie() plugin

<scripttype="text/javascript">
    $(document).ready(function() {
        // check for cookie on loadif( $.cookie('chk_ar') ) {
            console.log($.cookie('chk_ar'));
            var chk_ar = $.cookie('chk_ar');

            // convert string to object
            chk_ar = $.parseJSON(chk_ar);
            console.log(chk_ar);

            // loop through and apply checks to matching sets
            $.each(chk_ar, function(index, value) {
                console.log(value);
                $('input').filter('[data-at="'+value+'"]').prop('checked', true);
            });
        }
    });

    // handle checkboxes
    $('input[name="bg-noise-option[]"').on('click', function() {
        var check_array = [];

        // add to array
        $(':checked').each(function() {
            check_array.push($(this).attr('data-at'));
        });

        // stringify array object
        check_array = JSON.stringify(check_array);
        console.log(check_array);

        // set cookie
        $.cookie('chk_ar', check_array, {path:'/'});
    });
</script>

Post a Comment for "Set Jquery Cookie For Each Checkbox"