Skip to content
Advertisement

How do I make a checkbox that automatically refreshes the page without changing the values of inputs?

I’m trying to make a checkbox that will automatically refresh the page every few seconds or minutes when checked using JavaScript.

I found some ways to make it refresh the page, but when it does that, all of the inputs including the checkbox return to their default value. I want them to keep their current value when the page gets refreshed. How can I do that?

Here’s the HTML code:

<section id="menu">

    <div class="menu_item">
         From <input type="date" name="start_date" id="start_date"> To <input type="date" id="end_date" id="end_date">
         <button id="set_dates">Set dates</button>
    </div>

    <div class="menu_item">
         <input type="checkbox" name="auto_refresh" id="auto_refresh" checked> Auto refresh
    </div>

    <div class="menu_item">
         <input type="checkbox" name="show_desc" id="show_desc"> Show descriptions
    </div>

    <div class="menu_item">
         Column width <input type="number" name="col_width" id="col_width" min="100" max="5000" value="100" >
    </div>

</section>

I tried using this JavaScript code but it didn’t work as I expected:

let checkbox = document.getElementById("auto_refresh");

function auto_refresh() {
    if(checkbox.checked == true) {
        let timeoutID = setTimeout("window.location.reload()", 5000);
    } else {
        clearTimeout(timeoutID);
    }
}

if(checkbox.checked == true) {
    auto_refresh();
}
checkbox.onchange = auto_refresh;

I would appreciate some help and advice.

Advertisement

Answer

On every input change you can call a function and set the value to browser localStorage. Then, On page start(refresh), call a function to retrieve the data back from localStorage and set the view.

To set the value, localStorage.setItem("col_width", "100");

To retrieve the value, localStorage.getItem("col_width");

Advertisement