Have Checkbox Stay Checked Throughout Session

2020-07-30 03:41发布

问题:

I have a table where I can check a checkbox and it will log all of the contents in the row. There are some search functions and other buttons on the page, so I want to use session storage to be able to keep any checkboxes that are checked, checked, throughout refreshes until the page is closed. I have something from an example I found but it doesnt seem to be working. How could I fix this?

HTML for table column/row with checkboxes:

<td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid"></td>

JavaScript:

$(function(){
    var test = sessionStorage.input === 'false'? true: false;
    $('input').prop('checked', test || false);

    $('input').on('change', function() {
    sessionStorage.input = $(this).is(':checked');
    console.log($(this).is(':checked'));
});
});

回答1:

Take a look at this:

var test = sessionStorage.input === 'false'? true: false;

So what does it mean? If sessionStorage.input is false, return true, else false.

So when you check the checkbox then it's set to true, which by the above logic, since it's not false - test is evaluated as false.

Solution:

var test = sessionStorage.input === 'true';

This will set test to true if the session is also true.

You can also change $('input').prop('checked', test || false); to:

$('input').prop('checked', test);

The || false is unnecessary. Or even better/shorter:

$('input').prop('checked', sessionStorage.input === 'true');

And then you don't need the test variable at all.

As for your question "how can I make this work for individual checkboxes": You can use the checkbox id for example:

// save the individual checkbox in the session inside the `change` event, 
// using the checkbox "id" attribute
var $el = $(this);
sessionStorage[$el.prop('id')] = $el.is(':checked');

And then, when you refresh the page:

$(':checkbox').each(function() {
    // Iterate over the checkboxes and set their "check" values based on the session data
    var $el = $(this);
    $el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
});

So this is how it should look like:

$(function(){
    $('input:checkbox').each(function() {
        // Iterate over the checkboxes and set their "check" values based on the session data
        var $el = $(this);
        $el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
    });

    $('input:checkbox').on('change', function() {
        // save the individual checkbox in the session inside the `change` event, 
        // using the checkbox "id" attribute
        var $el = $(this);
        sessionStorage[$el.prop('id')] = $el.is(':checked');
    });
});

Working solution - Couldn't use stack-snippets because it doesn't support sessionStorage due to security limitations.