Search code examples
jqueryjqgridjqgrid-asp.netfree-jqgrid

free-jqgrid, after cancel row edit by escape key press, when I again edit by just selecting that row, it no longer remain set selected


I am using free jqgrid v4.9.2 in my asp.net project. Here in my jqgrid, I have implemented a functionality is, on select row, selected row became editable. Everything is working fine except by one condition. When first time I select row it get editable and selected too. But when I cancel row editing by pressing 'ESC' key and again select "THAT" row to edit, it get converted into editable mode but it does not get selected.

so when I press delete button, row not get delete, because its not selected but I had selected that row.

To get more understanding, here is my jqgrid code:

function RenderIGPLotDetailsGrid() {

var oGrid = $('#tbIGPLD'), topPagerSelector = '#' + $.jgrid.jqID(oGrid[0].id) + "_toppager", lastSel;

oGrid.jqGrid({
    url: sRelativePath + '/Ajax.asmx/GetDataForGrid',
    mtype: "POST",
    datatype: "json",
    ajaxGridOptions: { contentType: "application/json; charset=utf-8" },
    serializeGridData: function (data) {
        return JSON.stringify(data);
    },
    jsonReader: {
        root: "d.rows",
        page: "d.page",
        total: "d.total",
        records: "d.records"
    },
    colNames: ['UOMId', 'Lot #', 'Wt/Pkg.(Kgs)', 'No. of pkgs.', 'Pkg. type', 'Total Weight'],
    colModel: [
        { name: 'UOMId', index: 'UOMId', hidden: true },
        { name: 'LotNo', index: 'LotNo', editable: ($('#hftbIsManualLotNo').val() === '1'), editrules: { required: ($('#hftbIsManualLotNo').val() === '1') }, width: 50 },
        { name: 'GrossWeight', index: 'GrossWeight', template: editNumTemplate, width: 16, editoptions: { maxlength: 18} },
        { name: 'Qty', index: 'Qty', template: editNumTemplate, width: 15, editoptions: { maxlength: 18 },
            editoptions: {
                dataInit: function (domElem) {
                    $(domElem).on("blur", function () {
                        var iQty = $.trim($(this).val());
                        var selrow = oGrid.jqGrid('getGridParam', 'selrow');
                        var value = $('#' + selrow + '_GrossWeight').val() * iQty;
                        $('#' + selrow + '_TotalGrossWeight').val(value);
                    });
                }
            }
        },
        {name: 'UOM', index: 'UOM', template: colTemplate, width: 25, editable: true, edittype: 'select', formatter: 'select',
        editrules: {
            required: true,
            custom: true,
            custom_func: function (value) {
                if (value === g_sValueNONE)
                    return [false, "Selected UOM is invalid UOM. Please select a valid UOM before saving."];
                else
                    return [true, ""];
            }
        },
        editoptions:
            {
                value: eval('(' + g_oUOMList + ')'),
                dataEvents: [
                    { type: 'keyup', fn: function (e) { $(e.target).trigger('change'); } },
                    {
                        type: 'change',
                        fn: function (e) {
                            if (!e.isTrigger) {
                                var selrow = oGrid.jqGrid('getGridParam', 'selrow');
                                var uomId = $(this).val();
                                oGrid.jqGrid('setCell', selrow, 'UOMId', uomId);
                            }
                        }
                    }
                ]
            }
        },
        { name: 'TotalGrossWeight', index: 'TotalGrossWeight', template: editNumTemplate, width: 15, editoptions: { maxlength: 18 },  
            //Place this code in the col options of the last column in your grid
            // it listens for the tab button being pressed
            editoptions: {
                dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
                dataEvents: [
                    {
                        type: 'keydown',
                        fn: function (e) {
                            var key = e.charCode || e.keyCode;
                            if (key == 9)//tab
                            {
                                var iSalRow = oGrid.jqGrid('getGridParam', 'selrow');
                                //Save editing for current row.
                                oGrid.jqGrid('saveRow', iSalRow, { aftersavefunc: function (rowid) { SaveIGPLotDetails(oGrid, rowid); } });
                                //Made flag true to add new row after save opration grid reload
                                g_bIsTabClick = true;
                            }
                        }
                    }
                ]
            }
        }
    ],
    prmNames: { page: "pageIndex", rows: "pageSize", sort: "sortIndex", order: "sortDirection", search: "_search" },
    autowidth: true,
    search: false,
    postData: {
        filters: null,
        spName: 'GetIGPLotDetailsList',
        paramXML: $xmlDoc.html().toString()
    },
    width: 'auto',
    height: 'auto',
    rowNum: 20,
    rowList: [20, 50, 100, 150, 200],
    sortname: '',
    sortorder: 'asc',
    page: 1,
    gridview: true,
    toppager: true,
    autoencode: true,
    ignoreCase: true,
    viewrecords: true,
    caption: 'Lot Details',
    editurl: 'clientArray',
    footerrow: true,
    loadComplete: function (data) {
        updateJqGridButtonState($(this), jqGridMode.None)
        // During first time save, by default adding one editable row    
        if (data.d.rows.length <= 0) {
            oGrid.jqGrid('addRowData', 'jqg1', g_oColDefValues, 'first');
            oGrid.jqGrid('editRow', 'jqg1', { keys: true, aftersavefunc: function (rowid) { SaveIGPLotDetails($("#tbIGPLD"), rowid); } });
            oGrid.jqGrid("setSelection", 'jqg1', true);
        }

        //To create new rowm after pressing tab on last column of grid.
        if (g_bIsTabClick) {
            AddNewRow(oGrid);
            g_bIsTabClick = false;
        }
    },
    gridComplete: function () {
        $("table#tbIGPLD tr:last").addClass('ireg-jqgrid-lastrow');
        $("tr.footrow td").addClass('ireg-jqgrid-lastrow').addClass('ireg-jqgrid-footer');
        recalculateWidthInPercent('container', 'tbIGPLD', 0.98);
        var decTotalGrossWeight = $(this).jqGrid('getCol', 'TotalGrossWeight', false, 'sum');
        var decQty = $(this).jqGrid('getCol', 'Qty', false, 'sum');
        $(this).jqGrid('footerData', 'set', { TotalGrossWeight: decTotalGrossWeight, Qty: decQty });
        parent.g_decItemGrossWeight = decTotalGrossWeight;
    },
    //**Here it is a code which converts row into editable mode**
    onSelectRow: function (rowid) {
        // oSavedRows array is not empty if some row is in inline editing mode.
        var oSavedRows = oGrid.jqGrid("getGridParam", "savedRow");
        if (oSavedRows.length > 0) {
            // cancel editing of the previous selected row if it was in editing state.
            // jqGrid hold intern savedRow array inside of jqGrid object,
            // so it is safe to call restoreRow method with any id parameter
            // if jqGrid not in editing state.
            oGrid.jqGrid("restoreRow", oSavedRows[0].id);
        }

        oGrid.jqGrid("editRow", rowid, { keys: true,
            aftersavefunc: function (rowid) {
                SaveIGPLotDetails($("#tbIGPLD"), rowid);
            },
            afterrestorefunc: function (rowid) {
                var iRow = getRowIndex(rowid);
                if (!isValidGuid(rowid) && iRow !== 1)
                    oGrid.delRowData(rowid);
            }
        });
    }
}).jqGrid('navGrid', topPagerSelector, { add: false, edit: false, del: true, search: false, refresh: false
    Removed addParams & editParams because now rows will get editable based on click and will save on enter.
}, {}, {}, myDelParams, {}).jqGrid('inlineNav', topPagerSelector, {});

//iReg-2004: Removed all buttons expect delete
$("#" + $('#tbIGPLD')[0].id + "_top_iledit").remove();
$("#" + $('#tbIGPLD')[0].id + "_top_ilsave").remove();
$("#" + $('#tbIGPLD')[0].id + "_top_iladd").remove();
$("#" + $('#tbIGPLD')[0].id + "_top_ilcancel").remove();                        // #tbItems_top_ilcancel
$("#" + $('#tbIGPLD')[0].id + "_top_ildelete").remove();
$('.ui-separator').remove();                                                    // Separator after the delete button.

}

I google a lot to find out solution for this but i didn't find any relevant solution. I appreciate, if anyone address me resolve my this problem. Thank you


Solution

  • You code contains many suspected parts. The most suspected is the usage of fix 'jqg1' rowid in loadComplete. You can easy have id duplicates. I would recommend you to generate unique us using var newId = $.jgrid.randId(); and then use the id in addRowData. In general the usage of addRow. You can use initdata parameter of addRow to specify defaults.

    Moreover I would strictly recommend you to use inlineEditing parameter to specify inline editing options used in all calls. The current code which you use uses different options of editRow for the call inside of loadComplete and in onSelectRow. One uses afterrestorefunc another not uses. So ESC key in the first line works not in the same way like in other rows.

    One more problem in your code: you use selrow in many places of your code. Why? You could use $(this).closest("tr.jqgrow").attr("id") for example inside of blur change to get rowid of the current row. You can use oGrid.jqGrid("getGridParam", "savedRow")[0].id in other situations. Your current code require that the editing row will be selected. If you don't change the code then the usage of singleSelectClickMode: "selectonly" option is really required.

    If nothing above helps then you should provide the demo and step by step instruction which can be used to reproduce the problem in the demo.