Search code examples
jqueryajaxcheckbox

How to keep a checkbox checked?


How to keep selected checkbox checked after a dynamic search? After every search, the selected checkbox is unchecked.

Here is my code:
https://github.com/cdjordje/Test1.git

I tried this but it doesn`t work properly:

jQuery(function(){
    if (localStorage.input) {
        var checks = JSON.parse(localStorage.input);
        jQuery(':checkbox').prop('checked', function(i) {
            return checks[i];
        });
    }
});

jQuery(':checkbox').on('change', function() {
    localStorage.input = JSON.stringify(jQuery(':checkbox').map(function() {
        return this.checked;
    }).get());
});

Solution

  • Update your code in https://github.com/cdjordje/Test1.git according to below instructions.

    Update your index.php file

    Step 1: Add Function outside of document.ready in script of index.php file

    var checked_value_array = [];
      function getCheckedValue(THIS){
        var temp = $(THIS).val();
    
        if($("#lib_id_"+temp).prop('checked') == true){
          checked_value_array.push(temp);
        }else{
          checked_value_array = checked_value_array.filter(function(item) {
          return item !== temp
        });
        
      }
    }
    

    Step 2 : Replace load_data function in index.php file with below function

    function load_data(page, query = '')
        {
          var temp_arr = JSON.stringify(checked_value_array);
          $.ajax({
            url:"fetch.php",
            method:"POST",
            data:{page:page, query:query,temp_arr:temp_arr},
            success:function(data)
            {
              $('#dynamic_content').html(data);
            }
          });
        }
    

    Update your fetch.php file

    Step 1: Add below code in fetch.php file

    $checked_value_array =  json_decode($_POST['temp_arr']);
    

    Step 2 : Replace foreach loop in fetch.php with below foreach loop

    foreach($result as $row)
      {
        $checked = '';
        $id = $row['id'];
        if (in_array($id , $checked_value_array)){
          $checked = 'checked';
        }
    
        $output .= '
        <tr>
          <td>'.$row["id"].'</td>
          <td>'.$row["title"].'</td>
          <td><input class="chkCheckBoxId" type="checkbox" id="lib_id_'.$row['id'].'" onclick="getCheckedValue(this)" name="lib_id[]" value="'. $row['id'] .'"  '.$checked.'></td> 
        </tr>
        ';
      }