Skip to content
Advertisement

PHP / WP How to save checkbox status after refresh?

I have a filter that is list of country looped using foreach, I want to be able to save the checkbox’s status when I refresh the page. So for example if Japan is checked, it should stay checked when I refresh the page. How should I do it, I have seen some posts about using localstorage but does it work with my code that doesn’t have an “id”? Is it possible to do it by “name=”filter_country[]”? I also have a filter that is using “Radio” I am not sure if it works for both radio and checkbox.

<ul class="filter-country">
        <?php foreach($countries as $country):?>
        <li class="filter-child filter-item">
        <div class="checkbox">
          <label>
            <input type="checkbox" class="dir-filters filter-checkbox" name="filter_country[]" value="<?php echo $country;?>">
            <?php echo $country;?>
          </label>
        </div>
        </li>
        <?php endforeach;?>

Advertisement

Answer

That should work

// get all checkboxes
const countries = document.querySelectorAll('.filter-checkbox');

// when checked set its value to localstorage
countries.forEach(country => {
    country.addEventListener('change', () => {
        localStorage.setItem('checkedCountry', country.value);
    });
});

// checking for localstorage. If checkbox value is the same as value in localstorage we set it's attribute checked to be true
countries.forEach(country => {
    const checkedCountry = localStorage.getItem('checkedCountry');
    if(checkedCountry && checkedCountry === country.value ) {
        country.checked = true;
    }
});

Notice that checkboxes allows to be cheсked any number of countries but in this example we store only one value in localstorage. So only the last checked country will be checked after reload. If it’s not what are you looking for please inform

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement