【问题标题】:PHP / WP How to save checkbox status after refresh?PHP / WP如何在刷新后保存复选框状态?
【发布时间】:2021-02-07 13:45:35
【问题描述】:

我有一个过滤器,它是使用 foreach 循环的国家/地区列表,我希望能够在刷新页面时保存复选框的状态。因此,例如,如果选中日本,则在我刷新页面时它应该保持选中状态。我应该怎么做,我看过一些关于使用 localstorage 的帖子,但它是否适用于我没有“id”的代码?是否可以通过“name="filter_country[]" 来实现?我还有一个使用“Radio”的过滤器我不确定它是否适用于收音机和复选框。

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

【问题讨论】:

  • 我很想知道使用 WP 数据模型维护国家/地区列表的位置。它是类别/帖子还是自定义帖子类型。您提供的代码是 UI 端,但您如何在数据库中跟踪所选国家/地区?这个国家选择是用户特定的还是管理员用户设置的?

标签: php wordpress checkbox


【解决方案1】:

应该可以的

// 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;
    }
});

请注意,复选框允许选中任意数量的国家,但在此示例中,我们仅在本地存储中存储一个值。因此,重新加载后只会检查最后检查的国家/地区。如果不是你要找的请告知

【讨论】:

  • 嘿,谢谢你,它完全按照我的意愿工作!但是有可能让它一次拯救多个国家吗?它只适用于一个国家
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 2021-04-30
  • 1970-01-01
  • 2018-11-05
  • 2021-08-08
  • 1970-01-01
相关资源
最近更新 更多