我想在页面刷新或提交后保持复选框的状态。在我的代码中,复选框是在显示提交结果后的下拉按钮内,但不会保持检查状态。
这是我的HTML代码。
HTML:
<form method="GET" name="frm1" action="filter.php" id="form">
<div class="dropdown" id="myDropdown">
<button type="button" class="btn mr-2 mt-1 fillbtn" style="background-color:#494f4d; color: white; float:right; font-size:11px;" data-toggle="dropdown">
<i class="fa fa-filter" aria-hidden="true"></i> MOVIES
</button>
<div class="dropdown-menu dropdown-menu-right ml-4" style="background-color:black; width:100%; height:90%;">
<div class="row rounded rowtv" style="background-color:black; color:#d2d8d6;">
<h4 class="mb-3 mt-3 border-bottom" style=" margin:auto; color:#76ff03; font-family:bold;">Movies</h4>
</div>
<div class="row rounded rowtv" style="background-color:black; color:#d2d8d6;">
<div class="col-12 col-sm-6 col-md-6 col-lg-3 tvgen">
<h4>Genre</h4>
<div class="" style="display:inline-block; margin-left:15px;" >
<label class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input ids" name="search[]" value="action">
<span class="custom-control-indicator"></span>
<span class="custom-control-description" >Action</span>
</label><br>
<label class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input ids" name="search[]" value="adventure">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Adventure</span>
</label><br>
<label class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input ids" name="search[]" value="animation">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Animation</span>
</label><br>
<label class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input ids" name="search[]" value="biography">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Biography</span>
</label><br>
</div>
</div>
</div>
</form>
答案 0 :(得分:2)
下面的代码使用javascript和cookies来保持提交或页面刷新时的复选框状态。
使用Javascript:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var chks = document.querySelectorAll('input[name="search[]"]');
for (var i = 0; i < chks.length; i++) {
if (getCookie('search[' + chks[i].value + ']') == 'true') {
chks[i].checked = true;
}
}
for (var i = 0; i < chks.length; i++) {
chks[i].addEventListener('click', function() {
document.cookie = "search[" + this.value + "]=" + this.checked + "; expires=Thu, 18 Dec 2018 12:00:00 UTC; path=/";
});
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
});
</script>