简体   繁体   中英

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:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM