0

I have a form that utilizes jqGrid to display personalized info for the user to select from. Everything works fine however on the "Review" page there is an option to edit the form. When you click edit and go back into the form selections all values selected are retained except for the jqGrid portion of the form that uses the checkbox values. How can I have this value retained so the user doesn't have to make the selection again?

var myGrid;
var blnListsFound = true;
var blnGridLoading = false;

function fnInitialize() {
    // Initialize the screen
    fnLoadForm();

    $('#no_transactions').hide();

    // alert("fnInitialize(): JS loaded fine, no errors");
}

function fnACHSwapGetGrid() {
    blnListsFound = true;
    // make sure we have a from account

    if ($('#selFromAccount').val() == '0') {
        return;
    }


    $('#imgWaitselFromAccount').show(); // show loading icon

    var urlString = '';
    var urlParams = new Array();
    // urlParams['rc'] = escape($('#RC').val());
    urlParams['RC'] = escape($('#txtMenuRC').val());
    urlParams['acctNBR'] = escape($('#selFromAccount').val());

    // get application type from aryAccount
    for (act in aryAccount)     {
        if (aryAccount[act]['Number'] == urlParams['acctNBR']) {
            urlParams['Appl'] = aryAccount[act]['Application'];
            break;
        }
    }

    $.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 ()
                {

                    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

                },
                loadError: function (jqXHR, textStatus, errorThrown)
                {
                    blnGridLoading = false;
                    blnListsFound = false; // no data found for this account
                    // console.log("loadError() setting blnGridLoading=false and blnListsFound=false");

                    fnValidateAccount(); // Check that user has data available

                    //alert('HTTP status code: ' + jqXHR.status + '\n' +
                    //  'textStatus: ' + textStatus + '\n\n ' +
                    //  'errorThrown: ' + errorThrown);
                    //alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
                }
            })
            .navGrid('#pager', {edit: false, add: false, del: false, search: false, refresh: true});
    //$("#list").closest('.ui-jqgrid-bdiv').width($("#list").closest('.ui-jqgrid-bdiv').width() + 10);

    $('#imgWaitselFromAccount').hide(); // hide loading icon
    fnfldDisable("selToAccount", false);
}

function fnLoadForm() {
    for (swap in arySwap) {
        if ($('#selFromAccount').val() != 0) {
            break;            // populate just once
        }

        if (typeof arySwap[swap]['FromAccount'] != 'undefined' // have swap data
                && arySwap[swap]['FromAccount'] != ''               // and its not blank
                )
        {
            $('#selFromAccount').val(arySwap[swap]['FromAccount']);
            $('#selFromAccount').change(); // trigger change calls
            $('#selToAccount').val(arySwap[swap]['ToAccount']);
            $('#selToAccount').change(); // trigger change calls
        }
    }
}

function fnGetAccountTitle(objAccount, fldTitle) {
    if (typeof objAccount != 'object') {
        return false;
    }

    if (typeof fldTitle != 'string') {
        return false;
    }

    if ($('#' + fldTitle).length) {
        $('#' + fldTitle).val('');
        var curAccount = fnGetSelected(objAccount);

        for (act in aryAccount) {
            if (aryAccount[act]['Number'] == curAccount) {
                var Application = fldTitle.replace('Title', 'Application');
                $('#' + fldTitle).val(aryAccount[act]['Title']);
                $('#' + Application).val(aryAccount[act]['Application']);
                return;
            }
        }
    }
}

function fnValidateAccount() {
    var blndoSubmit = true;
    // console.log("fnValidateAccount() called.");
    $("#list").removeClass("errmark"); // reset error display

    if (blnGridLoading) {
        $("#no_data").hide();

        reValidateTimer = setTimeout("fnValidateAccount()", 2000);
        // console.log("Grid loading, retrying validation in 5 seconds");
        blndoSubmit = false;
    }
    else {
        var numRows = $("#list").jqGrid('getGridParam', 'records');     // rows available
        var selRows = $("#list").jqGrid('getGridParam', 'selarrrow');   // rows selected

        if (numRows < 1 || blnListsFound == false) {
            $("#no_transactions").show();
            $("#divTransactions").hide();

            fnDoInvalidData('list', 'No data was found for this account.', true);
            // $("#list").jqGrid('GridUnload');
            blndoSubmit = false;
        }
    }

    return blndoSubmit;
}

function fnValidate() {
    // Validate data that has been entered by the user.
    var blndoSubmit = true; // Should we submit the form?
    // console.log("fnValidate() " + new Date() );
    // console.log("fnValidate() called.");


    fnResetInvalidFields('frmData');    // Reset the fields marked as errored.

    if (!$('#chkSaveRecord').is(':checked')) {
        return true;
    }

    $('#CompanyIds').val(""); 

    if (!$('#chkEmailNone').is(':checked')) {
        if (!fnCheckEmail($('#txtEmail').val())) {
            fnDoInvalidData('txtEmail', 'Email Address is not valid.', true);
            blndoSubmit = false;
        }
    }

    var numRows = $("#list").jqGrid('getGridParam', 'records');
    var selRows = $("#list").jqGrid('getGridParam', 'selarrrow');
    // console.log(numRows + ' records loaded, ' + selRows.length + ' selected');

    accountValidated = fnValidateAccount();

    if (!accountValidated) {
        // function shows no_transactions container for us
        fnDoInvalidData('list', 'No data found for this account.', true);
        // console.log("validateAccount gave failure.");
        blndoSubmit = false;
    }

    var tmpselAccount = fnGetSelected('selFromAccount');
    if ((tmpselAccount == '') || (tmpselAccount == '0')) {  

        fnDoInvalidData('selFromAccount', 'Selection required.', true);
        blndoSubmit = false;
    }

    var tmpselAccount = fnGetSelected('selToAccount');
    if ((tmpselAccount == '') || (tmpselAccount == '0')) {  // swap to
        fnDoInvalidData('selToAccount', 'Selection is required.', true);
        blndoSubmit = false;
    }

    if (fnGetSelected('selFromAccount') == fnGetSelected('selToAccount')) {
        fnDoInvalidData('selToAccount', 'Selections must be different.', true);
        blndoSubmit = false;
    }

    // if undefined or no rows or no available
    if (!blnListsFound) {
        fnDoInvalidData('list', 'No data was found for this account.', true);
        blndoSubmit = false;
    }

    if (!accountValidated) {
        fnDoInvalidData('list', 'No data was found for this account.', true);
        blndoSubmit = false;

    }

    if (!blnGridLoading) {
        if (numRows && (typeof (selRows) === "undefined" || !selRows || !selRows.length)) {
            fnDoInvalidData('list', 'At least one item must be selected.', true);
            fnDoInvalidData('selFromAccount', 'At least one item must be selected.', true);

            blndoSubmit = false;
        }

        if (numRows && (typeof (selRows) !== "undefined" && selRows && selRows.length)) {
            // collect selected companyid rows from jqGrid
            var aryCompanyIds = [];
            for (var i = 0; i < selRows.length; i++) {
                aryCompanyIds.push(
                        $("#list").jqGrid('getCell', selRows[i], 'Routing')
                        + '=' + $("#list").jqGrid('getCell', selRows[i], 'CompanyId')
                        + '=' + $("#list").jqGrid('getCell', selRows[i], 'Description')
                        + '=' + $("#list").jqGrid('getCell', selRows[i], 'IndName')
                        );
            }
            // set values in hidden field
            $('#CompanyIds').val(aryCompanyIds.join("||"));
        }
    }
    else {
        // grid still loading
        blndoSubmit = false;
    }

    if (blndoSubmit === false) {
        fnACHSwapGetGrid();
    }

    return blndoSubmit;
}
svsdnb
  • 144
  • 1
  • 17
  • jqGrid 5.0.2 is the version if that helps – svsdnb May 02 '19 at 17:10
  • "user doesn't have to make the selection again" over what time frame, the life of the page or life of the session or a life beyond that? – jaybro May 02 '19 at 18:06
  • The session. If they opt for edit I would like the jqGrid checkbox to retain it's value as the other values not in jqGrid retain theirs for the edit. New user, default values. New session of same user, default values. Just only on the edit I want them retained. – svsdnb May 02 '19 at 19:36
  • 1
    could you use [sessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) to retain the jqGrid checkbox values? On edit, Build a javascript object of the names/values and use JSON.stringify() to serialize object and store in sessionStorage. Then in loadComplete, if the sessionStorage item is not null, use $.parseJSON() to de-serialize the string to get the object, then set your checkboxes. – jaybro May 02 '19 at 20:15
  • I tried $(':checkbox').each(function () { var status = localStorage.getItem(this.id) === "false" ? false : true; $(this).prop("checked", status); }); but this just makes the first item selected not the one I actually selected. – svsdnb May 02 '19 at 20:44
  • If I use sessionStorage all checkboxes are checked – svsdnb May 02 '19 at 20:46
  • I do not see form editing here, since it is disabled in navGrid or maybe you use custom form edit? Please if possible post a simple code that reproduces the problem, in your case is very difficult to reproduce it. – Tony Tomov May 06 '19 at 02:25
  • There's no simple code to post. There's a form, part of the form uses jqGrid. A selection can be made from the grid. User clicks, NEXT, and is presented with a Review page with the options to submit or edit. I do not need to edit the checked grid entry, this is to edit the overall form. I need the selection made in the jqgrid to retain it's value on reload for the session. – svsdnb May 06 '19 at 13:16

0 Answers0