Question

I'm trying to adapt some code we use to store if a checkbox is checked or not in a cookie so that when the page refreshes it will remember which boxes were checked or unchecked. The problem is the new element I'm trying to store isn't a checkbox now, it's basically an icon that has a class('selected') toggled on or off placing a checkmark next to it. This is the toggle function:

//share - add class and check on click
$('.share-actions li a').click(function(e) {
    e.preventDefault();
    $(this).toggleClass('selected');
});

And here's the cookie I'm trying to adapt:

var $checkboxes;

// set the cookie
function setcookie() {
    var options= $checkboxes.map(function() {
        if (this.checked) return this.name;
    }).get().join(',');

    $.cookie('new_cookie', options);
}

$(function() {
    $checkboxes = $('input:checkbox').change(setcookie);
});

var alreadySetCookies = $.cookie('new_cookie').split(',');

for (var $cookie in alreadySetCookies) {
    $("input[name='" + alreadySetCookies[$cookie] + "']").attr("checked", "checked");
}
Was it helpful?

Solution

Detecting the presence of the selected class instead of the checked state. With minimal alterations to the original code.

The event handler:

$('.share-actions li a').click(function(e) {
    e.preventDefault();

    $(this).toggleClass('selected');
    setcookie();
});

And the general cookie get/set code:

var $checkboxes = $('.share-actions li a');

function setcookie() {
    var options = $checkboxes.map(function() {
        if ($(this).hasClass('selected')) return $(this).attr('id');
    }).get().join(',');

    $.cookie('new_cookie', options);
}

var alreadySetCookies = $.cookie('new_cookie').split(',');

alreadySetCookies.forEach(function(id) {
    $("#" + id).addClass('selected');
});

Each "checkbox" will need a unique ID for this to work:

<ul class="share-actions">
    <li><a href="#" id="facebook">Facebook</a></li>
    <li><a href="#" id="twitter">Twitter</a></li>
    <li><a href="#" id="instagram">Instagram</a></li>
</ul>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top