0

I have a dataTable load all data from the MySql database, the first checkboxes are automatically increased when I add a new row and it will be checked (or unchecked) by users. I would like to keep the checkbox results when the page reload. But the issue is only the first checkbox on the first row works.

This is my Javascript

// Avoid scoping issues by encapsulating code inside anonymous function
(function() {
  // variable to store our current state
  var cbstate;
  
  // bind to the onload event
  window.addEventListener('load', function() {
    // Get the current state from localstorage
    // State is stored as a JSON string
    cbstate = JSON.parse(localStorage['CBState'] || '{}');
  
    // Loop through state array and restore checked 
    // state for matching elements
    for(var i in cbstate) {
      var el = document.querySelector('input[name="' + i + '"]');
      if (el) el.checked = true;
    }
  
    // Get all checkboxes that you want to monitor state for
    var cb = document.getElementsByClassName('save-cb-state');
  
    // Loop through results and ...
    for(var i = 0; i < cb.length; i++) {
  
      //bind click event handler
      cb[i].addEventListener('click', function(evt) {
        // If checkboxe is checked then save to state
        if (this.checked) {
          cbstate[this.name] = true;
        }
    
    // Else remove from state
        else if (cbstate[this.name]) {
          delete cbstate[this.name];
        }
    
    // Persist state
        localStorage.CBState = JSON.stringify(cbstate);
      });
    }
  });
})();
</script>```

It is my html and php code
`<div id="table-container">
                    <div id = "checkbox-container">
                    <form method="POST" action="action.php">
                    <table width="100%" border="1" id='dataTable'>
                    <?php
                    $username = $_SESSION["username"];
                    require_once("includes/connection.php");
                    $sql = "SELECT * from form where username = '$username'";
                    $result = $conn->query($sql);
                    echo '<tableborder="1">';
                    echo '<tr>';
                    echo '<th>已列印</th>';
                    echo '<th>選擇</th>';
                    echo '<th>流水編號</th>';
                    echo '<th>賬號</th>';
                    echo '<th>專案代碼</th>';
                    echo '<th>利潤中心</th>';
                    echo '<th>發生日</th>';
                    echo '<th>項目</th>';
                    echo '<th>科目</th>';
                    echo '<th>支出金額</th>';
                    echo '<th>有無單據</th>';
                    echo '<th>領收款人</th>';   
                    echo '<th>備註</th>';
                    //echo '<th>刪除</th>';
                    while ($output = mysqli_fetch_assoc($result)) {
                        echo '<tr>';
                        echo "<td><input type='checkbox' class='save-cb-state' name='mycheckbox' value='" .$output['id']. "'></td>";
                        echo "<td><input type='checkbox' name='checkbox[]' value='" .$output['id']. "'></td>";
                        echo '<td>'.$output['id'].'</td>';
                        echo '<td>'.$output['username'].'</td>';
                        echo '<td>'.$output['department'].'</td>';
                        echo '<td>'.$output['center'].'</td>';
                        echo '<td>'.$output['createdate'].'</td>';
                        echo '<td>'.$output['object'].'</td>';
                        echo '<td>'.$output['subject'].'</td>';
                        echo '<td>'.$output['total_money'].'</td>';
                        echo '<td>'.$output['receipt'].'</td>';
                        echo '<td>'.$output['name'].'</td>';
                        echo '<td>'.$output['note'].'</td>';
                        //echo '<td><input type="button" name="delete" value="刪除"></td>';
                        //echo "<td><button action='delete.php' method='POST' value='" .$output['id']. "' class='btn btn-danger'> Delete</button></td>";

                    };
                    echo '</table>';
                    ?>
                    </table>
                    <input type="submit" name="delete" id="delete" value="刪除">
                    <input type="submit" name="print_pdf" id="print_pdf" value="列印">
                    </form>
                    </div>
                </div>
MeanGreen
  • 3,098
  • 5
  • 37
  • 63
  • 1
    Check this question/answer: [How do I keep single checkbox stay checked after refreshing the page?](https://stackoverflow.com/q/44310386/2530491) – bpanatta Dec 24 '20 at 04:08
  • Does this answer your question? [Why does the checkbox stay checked when reloading the page?](https://stackoverflow.com/questions/299811/why-does-the-checkbox-stay-checked-when-reloading-the-page) – Shivam Puri Dec 24 '20 at 07:02
  • 1
    @ShivamPuri, it is not, my checkbox is on a while loop,these checkboxes are automatically increased when users add a new row and it will be checked (or unchecked) by users.And then I would like to keep the checkbox be checked (or unchecked) when the page reload. – Duc Tamm Chieu Dec 24 '20 at 08:22
  • @bpanatta The result is the same with my current code, only the checkbox on the first row worked. – Duc Tamm Chieu Dec 24 '20 at 08:27

1 Answers1

0

The problem lies in the name of the inputs:

  • You have multiple inputs with the same name 'mycheckbox';
  • The inputs with name 'checkbox[]' are too generic for saving the state.

To solve this change the name of the inputs based on an index counter, like the following:

echo "<td><input type='checkbox' class='save-cb-state' name='mycheckbox-$idx' value='" .$output['id']. "'></td>";
echo "<td><input type='checkbox' name='checkbox[$idx]' value='" .$output['id']. "'></td>";
$idx++;

In this example I have created an $idx variable, that holds an integer, to count each iteration and help creating different names for each input - we achieve this by adding the $idx variable to the input name.

bpanatta
  • 509
  • 3
  • 12