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

2
  • 1
    try prop method instead of attr as you did it in $("tr").each Commented Oct 9, 2020 at 10:23
  • Specifically this answer: stackoverflow.com/a/19630917/2181514 - you have to use .prop for checkboxes in jquery 3.5.1 Commented Oct 9, 2020 at 10:30

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.