Search code examples
javascriptcheckboxtabular

Sorting Table with checkbox: content is not visible anymore


This is the the HTML of a table and the JS code that I'm trying. Basically clicking a checkbox another table will appears:

<form class="filter">
<input type="checkbox" id="checkboxID" class="unchecked"> EG
<input type="checkbox" id="checkbox1OG" class="unchecked"> 1.OG
<input type="checkbox" id="checkbox2OG" class="unchecked"> 2.OG
<input type="checkbox" id="checkbox3OG" class="unchecked"> 3.OG
</form>

<script>

 $('input.unchecked').on('change', function() {
 $('input.unchecked').not(this).prop('checked', false);  
});

</script>


<script>

$("#checkboxID").change(function(){
$("#tableID tr.rowEG").toggle(!this.checked); 
});

    $("#checkbox1OG").change(function(){
$("#tableID tr.row1OG").toggle(!this.checked); 
});

    $("#checkbox2OG").change(function(){
$("#tableID tr.row2OG").toggle(!this.checked); 
});

    $("#checkbox3OG").change(function(){
$("#tableID tr.row3OG").toggle(!this.checked); 
});

</script>

But on click the table disappears.


Solution

  • The issue happens if you have a checkbox selected and then you select another one without deselecting manually the previous one. Otherwise it works well.

    I suggest you to define a function like this:

    function restore_table() {
        $("#tableID tr.rowEG").toggle(true);
        $("#tableID tr.row1OG").toggle(true);
        $("#tableID tr.row2OG").toggle(true);
        $("#tableID tr.row3OG").toggle(true);
    }
    

    Then you can call this function on each individual change() call before operating the table rows. For example:

    // Do this with the four change calls
    $("#checkboxEG").change(function(){
        restore_table();
        $("#tableID tr.rowEG").toggle(!this.checked); 
    });