我正在将复选框的选中状态保存在cookie中。我想在单击“重置”按钮时将所有复选框重置为未选中状态。 javascript我正在使用“重置”复选框,但是当我刷新页面时,检查状态又回来了。
HTML:
<form method="GET" name="frm1" action="filter.php" id="form">
<input type="reset" onclick="return resetForm();"/>
<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="sub1">
<span class="custom-control-indicator"></span>
<span class="custom-control-description" >sub1</span>
</label><br>
<label class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input ids" name="search[]" value="sub2">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">sub2</span>
</label><br>
</div>
</form>
脚本:
<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 "";
}
});
function resetForm() {
var expired = new Date(today.getTime() - 24 * 3600 * 1000); // less 24 hours
function deleteCookie(name)
{
document.cookie=name + "=null; path=/; expires=" + expired.toGMTString();
}
}
</script>
我在这里做什么错?请帮助我。
答案 0 :(得分:1)
尝试一下:-
代替此:-
<input type="reset" onclick="return resetForm();"/>
更改
<input type="button" value ="Reset cookie" onclick= 'document.cookie = "username=; expires=Fri, 29 Jun 2018 00:00:00 GMT";'/>