简体   繁体   中英

How to persist checkbox checked state after page reload?

页面刷新后,我无法保持选中的复选框

You need to use cookies for this... As soon as user clicks on check box, store its state into a cookie and just fetch the cookie value on page load to prepoulate the checkboxes as they were in previous selection.

HTML

<div>
  <label for="option1">Option 1</label>
  <input type="checkbox" id="option1">
</div>
<div>
  <label for="option2">Option 2</label>
  <input type="checkbox" id="option2">
</div>
<div>
  <label for="option3">Option 3</label>
  <input type="checkbox" id="option3">
</div>
<button>Check all</button>

Fetching checkboxes value and making a cookie out of them

var checkboxValues = {};
$(":checkbox").each(function(){
  checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })

Function to read cookies to prepopulate on load

function repopulateCheckboxes(){
  var checkboxValues = $.cookie('checkboxValues');
  if(checkboxValues){
    Object.keys(checkboxValues).forEach(function(element) {
      var checked = checkboxValues[element];
      $("#" + element).prop('checked', checked);
    });
  }
}

Working Fiddle

You have to do this on server side. Either with PHP, ASP.NET or whatever you use.

This is the only way.

Or , if your website is client-side only, then you would have to implement it without any page refreshing.

Here how I do it:

    <html>

<input type="checkbox" <?php echo file_get_contents(".cktest"); ?> onclick="getFileFromServer('write_ckfile.php?target=.cktest&value='+this.checked, function(text){ show_write(text)});"> cktest with php<br/>


<!-- with ajax read the checked attribut from file -->
<input id="withajax" type="checkbox" onclick="getFileFromServer('write_ckfile.php?target=.cktest&value='+this.checked, function(text){ show_write(text)});"> cktest with ajax<br/>


<script>
function getFileFromServer(url, doneCallback) {
    var xhr;

    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = handleStateChange;
    xhr.open("GET", url, true);
    xhr.send();

    function handleStateChange() {
        if (xhr.readyState === 4) {
            doneCallback(xhr.status == 200 ? xhr.responseText : null);
        }
    }
}

function show_write(text) {
  //alert(text);
}


// 
getFileFromServer(".cktest", function(x) { document.getElementById("withajax").checked=x;} );

</script>

</html>

and the file write_ckfile.php:

    <?php
$strtarget=$_GET['target'];


$status=$_GET['value']=="true"?"checked":"";
file_put_contents($strtarget, $status );



?>

I hope this helps. MiKL~

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM