从存储的localstorage值中设置多选选项

问题描述 投票:0回答:1

我正在尝试根据相应的localstorage值设置多个选择选项。

将值存储在localstorage中的数组中是有效的,但我需要帮助根据这些值选择表单中的选项。

localstorage中的值是从复选框中收集的,如下所示:

jQuery(document).ready(function(){
    var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
    checkboxes = jQuery(".add-selectie :checkbox");
    checkboxes.on("change", function(){
        checkboxes.each(function(){
            checkboxValues[this.id] = this.checked;
        });
        localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    });
    jQuery.each(checkboxValues, function(key, value) {
        jQuery('#' + key).prop('checked', value);
    });
});

这样可以使用localstorage中的键“checkboxValues”将值保存在数组中,如下所示:

{"value1":true,"value2":true,"value3":false}

但是,如果在localstorage中找到值并且设置为true,我如何在表单中预先填充选择选项?

我制作了包含以上所有代码的this pen +演示表格。任何帮助将不胜感激!

javascript jquery html forms local-storage
1个回答
0
投票

下面的代码应该为您提供片段,通过读取localStorage中的值来更新选项元素的选定状态。

请注意,在stackoverflow执行上下文中使用localStorage存在安全问题

  • 我创建了一个具有类似方法的自定义单例/静态类CustomLocalStorage
  • 另外,我使用完整的对象OptionValueObject来支持复选框和选择元素的属性。

var CustomLocalStorage = (function() {
  var items = {};

  function getItem(itemKey) {
    for (var _itemKey in items) {
      if (_itemKey === itemKey) {
        return JSON.parse(items[itemKey]);
      }
    }

    return null;
  }

  function setItem(itemKey, itemValue) {
    items[itemKey] = JSON.stringify(itemValue);
  }

  return {
    getItem: getItem,
    setItem: setItem
  }
})();

function OptionValueObject(id, label, value) {
  this.id = id; // Used to identify checkboxes
  this.label = label; // Not used in this example
  this.value = value; // To bind it to select > option > value property
  this.checked = true; // To bind it to checkbox > checked property
}

$(document).ready(function() {

  function initialize() {
    initializeData();
    initializeUi();
  }

  function initializeData() {
    var optionValueObjects = [];
    optionValueObjects.push(new OptionValueObject(1, 'Label of option 1', 'value1'));
    optionValueObjects.push(new OptionValueObject(2, 'Label of option 2', 'value2'));
    optionValueObjects.push(new OptionValueObject(3, 'Label of option 3', 'value3'));

    CustomLocalStorage.setItem('options', optionValueObjects);
  }

  function initializeUi() {
    var optionValueObjects = CustomLocalStorage.getItem('options');
    for (var i = 0; i < optionValueObjects.length; i++) {
      var optionValueObject = optionValueObjects[i];
      var id = optionValueObject.id;
      
      // Checkbox: Identify element and set UI related property
      var checkboxElement = $('#checkbox' + id);
      checkboxElement.prop('checked', optionValueObject.checked);
      console.log(optionValueObject.value);
      // Option: Identify element and set UI related property
      var optionElement = $("#optionsSelect > option[value='"+ optionValueObject.value +"']");
      optionElement.prop('selected', optionValueObject.checked);
    }
  }

  function handleEvents() {

    function checkboxChangeHandler() {
      // Get the object, update the checked property and save it back
      
      // 1. Get the object
      var id = $(this).prop('id');
      var optionValueObjects = CustomLocalStorage.getItem('options');
      var optionValueObject = optionValueObjects.filter(function(optionValueObject) {
        if (('checkbox' + optionValueObject.id) === id) {
          return optionValueObject;
        }
      })[0];
      
      // 2. Update the checked property
      var checked = $(this).prop('checked');
      optionValueObject.checked = checked;
      
      // Bind the checked property to options selected property
      var optionElement = $("#optionsSelect > option[value='"+ optionValueObject.value +"']");
      optionElement.prop('selected', optionValueObject.checked);

      // 3. Save it back
      CustomLocalStorage.setItem('options', optionValueObjects);
    }

    $('#checkbox1').change(checkboxChangeHandler);
    $('#checkbox2').change(checkboxChangeHandler);
    $('#checkbox3').change(checkboxChangeHandler);
  }

  initialize();
  handleEvents();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="add-selectie">
  <input id="checkbox1" class="selector" type="checkbox"><label for="checkbox1">Value 1</label>
  <input id="checkbox2" class="selector" type="checkbox"><label for="checkbox2">Value 2</label>
  <input id="checkbox3" class="selector" type="checkbox"><label for="checkbox3">Value 3</label>
</div>

<form>
  <select id="optionsSelect" multiple="multiple">
    <option value="value1">Value 1</option>
    <option value="value2">Value 2</option>
    <option value="value3">Value 3</option>
  </select>
</form>
© www.soinside.com 2019 - 2024. All rights reserved.