Patrick Patrick - 1 year ago 82
HTML Question

javascript reload html page only when checkbox is checked

I would like to reload my page every x seconds if a checkbox is checked.

I found a code snipped for the reload and added an if statement.

But it doesn't work. The script only works without the if statemant.
What do I miss?

<!-- Reload page-->
if (document.getElementById('CheckBoxReloadPage').checked)
document.getElementById("CheckBoxReloadPage").checked = true;



Answer Source

Your page is correctly reloaded after 5 seconds, but only if you checked the checkbox in the first 5 seconds after your page has loaded.

If you want the check to occur every 5 seconds instead of 5 seconds from now, change setTimeout to setInterval.

Then, as you may imagine, when your page reloads, everything will be back to the way it was - including the checkbox. You will have to store the state of your checkbox in, say, the session storage and set it to your checkbox upon loading:

// Gets the reference of the checkbox once and for all
var myCheckbox = document.getElementById('CheckBoxReloadPage');

// Sets the initial value of the checkbox to the stored state
myCheckbox.checked = sessionStorage.getItem('checkbox-state');

// Listen to every change on the checkbox
myCheckbox.addEventListener('change', function (event) {
    // Store the state of the checkbox to the session storage

setInterval(function() {
    if (myCheckbox.checked) {
}, 5000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download