[英]How to check & uncheck checkbox onload function?
I have a code in which if my checkbox is checked and if I load window(page) checkbox should remain there on reload OR if I uncheck the checkbox and reload page then checkbox should remain unchecked.我有一个代码,如果我的复选框被选中并且如果我加载窗口(页面)复选框应该在重新加载时保留在那里,或者如果我取消选中复选框并重新加载页面,那么复选框应该保持未选中状态。 my code is as following.
我的代码如下。
<input type="checkbox" id="chk"> <script> window.onload = onPageLoad(); function onPageLoad() { if (document.getElementById("chk").checked == true) { document.getElementById("chk").checked = true; } else { document.getElementById("chk").checked = false; } } </script>
However above code returns unchecked checkbox even after reloading page after checking checkbox.但是,即使在选中复选框后重新加载页面后,上面的代码也会返回未选中的复选框。
Just add "checked" attribute to HTML tag:只需将“checked”属性添加到 HTML 标签:
<input type="checkbox" checked>
But if you need to keep checked input after page reload you need to add a storage info.但是,如果您需要在页面重新加载后保持检查输入,则需要添加存储信息。 Maybe help:
也许有帮助:
<input type="checkbox" id="chk">
<script>
window.addEventListener('load', function() {
document.querySelector("#chk").addEventListener('change', function(el) {
console.log(el.target.checked);
localStorage.setItem('input_checked', el.target.checked );
});
if ( localStorage.getItem('input_checked') !== null ) {
document.querySelector('#chk').checked = localStorage.getItem('input_checked') === 'true';
}
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.