设置并使用localStorage在表单编辑过程中保留复选框选择

时间:2019-05-02 21:42:03

标签: javascript jquery jqgrid local-storage

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

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

$.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);
});

1 个答案:

答案 0 :(得分:2)

展示位置

您当前getItem的位置是正确的。您也应该在此处放置setItem块。在loadComplete内部,这意味着一旦加载jqGrid,您的getItem将运行,并且setItem事件也将绑定到复选框。

localStorage机制

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状态,左侧可能会有一个带有sessionStorage和{{1}的面板}

逻辑

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

即使是,我们也要对其进行分解:

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; 的值,因为null为类型为object
  • 如果是对象,请立即将object设置为status。因为当您将值设置为falsetrue时,它将是字符串类型,而不是对象。
  • 如果不是对象类型,则检查与false'true'比较的值并进行相应设置。

这是最终的逻辑:

'false'

摘要

最后一些代码,看看代码片段, 请注意,因为iframe试图修改localStorage,浏览器将返回错误。但请在最后提取代码以查看结果。

let status = typeof localStorage.getItem($(this).attr('id')) === 'object' ? false : localStorage.getItem($(this).attr('id')) === 'true';
$(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;
}