[英]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.