Skip to content
Advertisement

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.

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement