簡體   English   中英

頁面重新加載后如何保持復選框選中狀態?

[英]How to persist checkbox checked state after page reload?

頁面刷新后,我無法保持選中的復選框

為此,您需要使用cookie。用戶單擊復選框后,將其狀態存儲到cookie中,然后只需在頁面加載時獲取cookie值,就可以像以前選擇復選框一樣預先填充復選框。

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

獲取復選框的值並使用它們制作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〜

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM