页面重新加载后如何保持复选框处于选中状态?
问题描述:
刷新页面后,我无法保留复选框选中.
I am unable to persist checkbox checked after page is refreshed.
答
您需要为此使用cookie ...用户单击复选框后,将其状态存储到cookie中,然后在页面上获取cookie值加载以像以前选择时一样预先填充复选框.
You need to use cookies for this... As soon as user clicks on check box, store its state into a cookie and just fetch the cookie value on page load to prepoulate the checkboxes as they were in previous selection.
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);
});
}
}