0

I'm trying to make it so clicking on a table row checks off a checkbox, as well as use localStorage to save the value so when the page is refreshed previously checked box's remain checked.

The code below accomplishes both of these. However, together they cause the checkbox's previously checked (from localStorage) to no longer be toggled by clicking on the row and require you to click directly on the box.

<script>

$("tr").each(function(e){
    $("input[type='checkbox']", this).each( function() {
        if (localStorage.getItem(this.value) == 'true') {
            $(this).prop("checked", true)};
    });
});

$("tr").on("click", function(e){
    $("input[type='checkbox']", this).each( function() {
        $(this).attr('checked', !$(this).attr('checked'));
        localStorage.setItem(this.value, this.checked);
    });
});

</script>

version used: bootstrap-4.5.2, jquery-3.5.1.slim

1 Answers1

2

$(this).attr('checked') will always return a string (see .attr) docs). So doing a ! on it will always result in false (unless it was an empty string, but in your code that cannot happen).

Simplify it to

this.checked = !this.checked;
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317