如何在页面重新加载后保持复选框已选中状态

How to persist checkbox checked state after page reload?

本文关键字:复选框 状态 加载 新加载      更新时间:2023-09-26

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

您需要使用cookie…一旦用户单击复选框,将其状态存储到一个cookie中,并在页面加载时获取cookie值,以预填充复选框,就像它们在以前的选择中一样。

<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>

获取复选框值并从中生成cookie

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

读取cookie以在加载时预填充的函数

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

您必须在服务器端执行此操作。PHP, ASP。. NET或其他你使用的。

这是唯一的办法。

,如果你的网站只是客户端,那么你将不得不实现它没有任何页面刷新。

我是这样做的:

    <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>

和write_ckfile.php文件:

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

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

?>

我希望这对你有帮助。MiKL ~