how to keep checkbox checked even after page refresh

1.3k views Asked by At

I have one checkbox on my form working with the database for active(1) and inactive(0) users to access via admin panel. All is working fine but the problem is its not keeping the record for the checboxes when the checkbox is checked or unchecked after refreshing/reloading the page. i want them to be remembered even after admin logout and login again. can any one help me out ? Thanx in advance

Here is HTML :

<td><input type='checkbox' class='user_status' 
       id='user_status_<?php echo $data['user_reg_id']; ?>' value='' name = 'user_status' 
                                onclick="userId(<?php echo $data['user_reg_id']; ?>)" />

Here is JS :

<script>
function userId(user_reg_id){
     $(document).ready(function(){
        var link =  "<?php echo base_url();?>" ;
            var st = $('#user_status_'+user_reg_id).is(":checked") ? 0 : 1; 
            $.post(link + "administration/um/user_status", {user_reg_id:user_reg_id, user_reg_status:st,  ajax : 1}, function(data){
                      alert (st); //showing status 1 and 0 on alert
  if (st == 1){
                          $("#user_status_").prop(":checked", true)
                             } else {
                          $("#user_status_").prop(":checked", false)
                     }; 
            });
    }); 
}
</script>
2

There are 2 answers

3
virendra On

store checkbox value in database using ajax when you click on it.. also fetch from database checkbox value if checkbox value is 1 than checked ...otherwise uncheck :)

0
EternalHour On

Since you need the data to be persistent, I would suggest using HTML5 localStorage. Depending on how persistent, you may need to save it in a database. I haven't tested this code and have not actually done this. It's meant to get you close to a working solution.

function isChecked(user_reg_id){
    $(document).ready(function(){ 
        $('#user_status_'+user_reg_id).on('click', function () {
            if(localStorage && localStorage.getItem(user_reg_id)){
                localStorage.removeItem(user_reg_id);
            }else{
                $('#user_status_'+user_reg_id).prop('checked', true);
            }
        }
    });
}