【问题标题】:Set and use localStorage to retain checkbox selections during form edit设置和使用 localStorage 在表单编辑期间保留复选框选择
【发布时间】:2019-05-02 21:42:03
【问题描述】:

我有一个表单,它使用jqGrid 作为表单的一部分。此部分显示可以通过复选框选择的用户信息。在评论页面上有一个编辑表单的选项,我试图在此过程中保留复选框选择。

我正在尝试为此使用window.localStorage,但是我不确定如何正确设置项目。我在 loadComplete 中调用 getItem ,我的编码在这里也可能不太正确。我现在所拥有的,当用户进行编辑时,选择 jqGrid 中的第一个项目而不是实际保存的项目。我猜是因为我没有正确设置项目。谁能提供指导?

$.jgrid.gridUnload("#list");

myGrid = $("#list").jqGrid({
    url: baseURL + '/scripts/get_user_list.php' + urlString,
    datatype: "json",
    mtype: 'POST',
    width: 660,
    height: '100%',
    pager: '#pager',
    rowNum: 10,
    rowList: [20, 30, 40, 50, 60],
    sortname: 'id',
    sortorder: "asc",
    viewrecords: true,
    multiselect: true,
    repeatitems: false,
    imgpath: '/scripts/jquery-ui/images',

    colNames: ['id', 'Building', 'Company ID', 'Description', 'Individual Name', 'SECCode'],
    colModel: [
        {name: 'id', index: 'id', jsonmap: 'id', hidden: true, width: 20},
        {name: 'Building', index: 'Building', jsonmap: 'Building', hidden: true, width: 20},
        {name: 'CompanyId', index: 'CompanyId', jsonmap: 'CompanyId', width: 110},
        {name: 'Description', index: 'Description', jsonmap: 'Description', sortable: true, width: 300},
        {name: 'IndName', index: 'IndName', jsonmap: 'IndName', width: 200},
        {name: 'UsrNum', hidden: true, index: 'UsrNum', jsonmap: 'UsrNum'}
    ],
    jsonReader: {
        repeatitems: false,
        root: 'rows',
        id: '0',
        cell: '',
        subgrid: {
            root: 'rows',
            id: '0',
            cell: '',
            repeatitems: false
        }
    },

    // subgrid support
    subGrid: true,
    subGridUrl: baseURL + '/scripts/get_user_list.php' + urlString,
    subGridModel: [{
        name: ['Date', 'ID'],
        params: ['CompanyId'],
        align: ['center', 'right'],
        width: [150, 80]
    }
    ],

    ondblClickRow: function (id) {
        $('#recId').val(id);
    },


    beforeRequest: function () {
        blnGridLoading = true;
        // console.log("beforeRequest(); setting blnGridLoading=true");
        fnValidateAccount(); // Check that user has data available
    },
    loadComplete: function () {

        $(':checkbox').each(function () {
            var status = localStorage.getItem(this.id) === "false" ? false : true;
            $(this).prop("checked", status);
        });

        blnGridLoading = false;
        // console.log("loadcomplete(); setting
        blnGridLoading = false;
        // ");

        for (swap in arySwap) {
            if (typeof arySwap[swap]['CompanyId'] != 'undefined') {

                $("#list").jqGrid('setSelection', arySwap[swap]['CompanyId']); // select companyId
            }
        }
        fnValidateAccount(); // Check that user has data available

    },
});

这是 loadComplate 中的 localStorage.getItem,与其余代码隔离:

$(':checkbox').each(function () {
    var status = localStorage.getItem(this.id) === "false" ? false : true;
    $(this).prop("checked", status);
});

这是我为 setItem 尝试的内容,但我不确定将其放置在哪里,或者这是否是正确的方法。

$(':checkbox').on('change', function () {
    //set the check value of checkbox
    localStorage.setItem(this.id, this.checked);
});

【问题讨论】:

  • 使用哪个版本的 jqGrid - Guriddo jqGrid、free-jqGrid 或 jqGrid 版本
  • 5.0.1 是版本号
  • 用什么编辑模块? - 从导航器编辑 jqGrid 表单或使用自定义表单编辑记录。我你用jqGird表单编辑请贴代码进行编辑。
  • 这是一个自定义表单。编辑按钮从会话中调用数据库中的值。除了 jqGrid 中的值外,所有其他值都被正确调用。该表单由 3 个文本字段、2 个下拉菜单和一个填充在 jqGrid 中的列表组成。
  • 你能添加一个 jsfiddle 或 sn-p 以便我们测试这段代码吗?

标签: javascript jquery jqgrid local-storage


【解决方案1】:

展示位置

您当前的getItem 位置是正确的。你也应该把setItem 块放在那里。在loadComplete 内部,这意味着一旦加载了jqGrid,您的getItem 就会运行,setItem 事件也将绑定到复选框。

本地存储机制

localStorage 只支持存储键值对,值只能是String。这意味着如果您将键 customCheckbox 设置为 true 并对该键运行查询,则返回值将是 "true"

localStorage.setItem('test', true); // item set
localStorage.getItem('test') // returns "true"; string, not boolean.

但是,有一种方法可以定义一个键并将对象存储到该键。您应该在存储之前使用JSON.stringify(),在检索之后使用JSON.parse()

let person = {name: 'John', age: 30, weight: 60} // a pure object.
localStorage.setItem('testPerson', JSON.stringify(person)); // object stringified;

localStorage.getItem('testPerson') // returns a stringified version of 'person' object;

// to use the stored stringified object like a regular object, you need to parse it.
person = JSON.parse(localStorage.getItem('testPerson'));

在您的代码中

您为每个不同的复选框使用了不同的键,因此您的键和值对于整个脚本或同一页面上的某些其他脚本都是开放的。您可能会意外删除或修改这些键的值,或者可能不会。此外,其他页面可以修改这些项目,因为它们在 localStorage 上。所以尽量设置唯一键。

注意:打开浏览器检查器并检查storage选项卡以检查您的localStorage状态,左侧可能有一个面板,带有sessionStoragelocalStorage

逻辑

现在让我们谈谈您当前的逻辑。看起来在初始页面加载时,当没有localStorage 的键时,您的所有复选框都会被选中。这是故意的吗?

就算是这样,我们还是分解一下吧:

var status = localStorage.getItem(this.id) === "false" ? false : true;

如果没有这样的密钥集,localStorage.getItem('key') 将返回 null。所以null === "false" 返回false 并且您的三元逻辑将status 设置为true

因此:

$(this).prop("checked", status); // sets all the checkboxes to checked at initial page load;

你应该做的是:

  • 检查键查询是否返回typeof object的值,因为null是typeof object
  • 如果是对象,请立即将status 设置为false。因为当您将值设置为 truefalse 时,它将是字符串类型,而不是对象。
  • 如果不是对象类型,则检查与'true''false' 比较的值并进行相应设置。

这是最终的逻辑:

let status = typeof localStorage.getItem($(this).attr('id')) === 'object' ? false : localStorage.getItem($(this).attr('id')) === 'true';

片段

最后一些代码,看看sn-p, 注意浏览器会返回错误,因为 iframe 试图修改 localStorage。但在你最后提取代码以查看结果。

$(document).ready(function() {
  $(':checkbox').each(function() {
    let status = typeof localStorage.getItem($(this).attr('id')) === 'object' ? false : localStorage.getItem($(this).attr('id')) === 'true';
    $(this).prop('checked', status);
    // console.log(status, typeof localStorage.getItem($(this).attr('id')))
  });

  // setItem.

  $(':checkbox').on('change', function() {
    //set the check value of checkbox
    localStorage.setItem($(this).attr('id'), $(this).prop('checked'));
    console.log('updated, ', $(this).attr('id'));
    console.log(localStorage);
  });

  $('#clear').on('click', function() {
    localStorage.clear();
  });
});
h3 {
  margin: 40px 0;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js'></script>


<div class="container">
  <div class="row">
    <div class="col-12">
      <h3>Checkboxes status to LocalStorage</h3>
      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" id="customCheck1">
        <label class="custom-control-label" for="customCheck1">One</label>
      </div>
    </div>
    <div class="col-12">
      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" id="customCheck2">
        <label class="custom-control-label" for="customCheck2">Two</label>
      </div>
    </div>
    <div class="col-12">
      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" id="customCheck3">
        <label class="custom-control-label" for="customCheck3">Three</label>
      </div>
    </div>
    <div class="col-12">
      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" id="customCheck4">
        <label class="custom-control-label" for="customCheck4">Four</label>
      </div>
    </div>
    <div class="col-12">
      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" id="customCheck5">
        <label class="custom-control-label" for="customCheck5">Five</label>
      </div>
    </div>
    <div class="col-12">
      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" id="customCheck6">
        <label class="custom-control-label" for="customCheck6">Six</label>
      </div>
    </div>
    <div class="col-12">
      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" id="customCheck7">
        <label class="custom-control-label" for="customCheck7">Seven</label>
      </div>
    </div>
    <div class="col-12">
      <div class="form-group"></div>
      <button id="clear" type="button" class="btn btn-danger">Clear LocalStorage</button>
    </div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2018-11-01
    • 2021-04-09
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    相关资源
    最近更新 更多