Sorting of columns when inline edit

2020-05-05 00:15发布

问题:

Not sure if that is a limitation or not. not able to sort any column when inline edit is there for at least one row.

Fiddle: http://fiddle.tinymce.com/nMfaab/1

steps:

  1. click Search button
  2. Select one or more rows
  3. Click "Change Value" button -> All selected rows should be now inline edit
  4. Now try to Sort on any column

    <!DOCTYPE html>
    

    SKumar - JQGrid -->

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery-ui-multiselect/1.13.6/jquery.multiselect.js"></script>
    <style type="text/css">
        html, body { font-size: 75%; }
        #gridSearchResult {
            height: 460px;
        }
    </style>
    <script type="text/javascript">
        $.jgrid = $.jgrid || {};
        $.jgrid.no_legacy_api = true;
        $.jgrid.useJSON = true;
    </script>
    <!--<script src="http://rawgit.com/free-jqgrid/jqGrid/master/js/jquery.jqgrid.src.js"></script> -->
    <script src="https://rawgit.com/free-jqgrid/jqGrid/master/js/jquery.jqgrid.src.js"></script>
    <!--<script src="jqGrid/js/jquery.jqGrid.src.js"></script>-->
    <script type="text/javascript">
    //<![CDATA[
        /*global $ */
        /*jslint eqeq: true, browser: true, plusplus: true */
        $(function () {
            "use strict";
            var $grid = $("#list"),
                gridData,
                startTime,
                measureTime = false,
                timeInterval,
                myDefaultSearch = "cn",
                getColumnIndexByName = function (columnName) {
                    var cm = $(this).jqGrid('getGridParam', 'colModel'), i, l = cm.length;
                    for (i = 0; i < l; i += 1) {
                        if (cm[i].name === columnName) {
                            return i; // return the index
                        }
                    }
                    return -1;
                },
                modifySearchingFilter = function (separator) {
                    var i, l, rules, rule, parts, j, group, str, iCol, cmi, cm = this.p.colModel,
                        filters = $.parseJSON(this.p.postData.filters);
                    if (filters && typeof filters.rules !== 'undefined' && filters.rules.length > 0) {
                        rules = filters.rules;
                        for (i = 0; i < rules.length; i++) {
                            rule = rules[i];
                            iCol = getColumnIndexByName.call(this, rule.field);
                            cmi = cm[iCol];
                            if (iCol >= 0 && ((typeof (cmi.searchoptions) === "undefined" ||
                                  typeof (cmi.searchoptions.sopt) === "undefined")
                                 && rule.op === myDefaultSearch) ||
                                    (typeof (cmi.searchoptions) === "object" &&
                                        $.isArray(cmi.searchoptions.sopt) &&
                                        cmi.searchoptions.sopt[0] === rule.op)) {
                                // make modifications only for the 'contains' operation
                                parts = rule.data.split(separator);
                                if (parts.length > 1) {
                                    if (typeof filters.groups === 'undefined') {
                                        filters.groups = [];
                                    }
                                    group = {
                                        groupOp: 'OR',
                                        groups: [],
                                        rules: []
                                    };
                                    filters.groups.push(group);
                                    for (j = 0, l = parts.length; j < l; j++) {
                                        str = parts[j];
                                        if (str) {
                                            // skip empty '', which exist in case of two separaters of once
                                            group.rules.push({
                                                data: parts[j],
                                                op: rule.op,
                                                field: rule.field
                                            });
                                        }
                                    }
                                    rules.splice(i, 1);
                                    i--; // to skip i++
                                }
                            }
                        }
                        this.p.postData.filters = JSON.stringify(filters);
                    }
                },
                dataInitMultiselect = function (elem) {
                     setTimeout(function () {
                         var $elem = $(elem), id = elem.id,
                             inToolbar = typeof id === "string" && id.substr(0,3) === "gs_";
                             options = {
                                 selectedList: 2,
                                 height: "auto",
                                 checkAllText: "All",
                                 uncheckAllText: "None",
                                 noneSelectedText: "Any",
                                 open: function () {
                                     var $menu = $(".ui-multiselect-menu:visible");
                                     $menu.width("auto");
                                     return;
                                 }
                             };
                         if (inToolbar) {
                             options.minWidth = 'auto';
                         }
                         $elem.multiselect(options);
                         $elem.siblings('button.ui-multiselect').css({
                             width: inToolbar? "98%": "100%",
                             marginTop: "1px",
                             marginBottom: "1px",
                             paddingTop: "3px"
                         });
                     }, 50);
                 };
    
    
            var date = new Date(), t = Object.prototype.toString.call(date), t1 = String(date);
    
            $( "#search" ).click(function() {
                var statesAsString = getStates();
                startTime = new Date();
                $grid.jqGrid({
                    datatype: 'json',
                    url: 'https://api.myjson.com/bins/efhbt',
                    mtype: 'GET',
                            colNames: ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg', 'hh', 'ii', 'Priority', 'Due Date', 'll', 'mm'],
                    colModel: [
                        { name: "aa", width: 200, label: "c01", frozen: true },
                        { name: "bb", width: 200, label: "c02", frozen: true },
                        { name: "cc", width: 100, label: "c03", frozen: true, search: true,
                            stype:'select', 
                                searchoptions: {
                                     sopt: ['eq','ne'],
                                     value: statesAsString,
                                     attr: {multiple: 'multiple', size: 3},
                                     dataInit: dataInitMultiselect
                                 }
                        },
                        { name: "dd", width: 100, label: "c04" },
                        { name: "ee", width: 100, label: "c05" },
                        { name: "ff", label: "c06" },
                        { name: "gg", label: "c07", editable: true, stype: 'select', formatter: 'select',
                            edittype: 'select', editoptions: {
                                value: 'Select:Select;Y:Yes;N:No',
                                multiple: false
                            }
                        },
                        { name: "hh", label: "c08", editable: true, stype: 'select', formatter: 'select',
                            edittype: 'select', editoptions: {
                                value: 'Select:Select;Y:Yes;N:No',
                                multiple: false
                            }
                        },
                        { name: "ii", label: "c09", editable: true, stype: 'select', formatter: 'select',
                            edittype: 'select', editoptions: {
                                value: 'Select:Select;Y:Yes;N:No',
                                multiple: false
                            }
                        },
                        { name: "jj", label: "c10", width: 100, editable: true },
                        { name: "kk", label: "c11", width: 100, editable: true, 
                            formatter:'date', formatoptions: {newformat:'Y-m-d'}, datefmt: 'Y-m-d',
                            editoptions: {
                                size:20, 
                                dataInit: function(el){ 
                                    $(el).datepicker({
                                        dateFormat: 'yy-mm-dd',
                                        changeYear: true,
                                        changeMonth: true,
                                        showWeek: true,
                                        yearRange: '1999:+1',
                                        minDate: new Date()
                                    }); 
                                }, 
                                defaultValue: function(){ 
                                    var currentTime = new Date(); 
                                    var month = parseInt(currentTime.getMonth() + 1); 
                                    month = month <= 9 ? "0"+month : month; 
                                    var day = currentTime.getDate(); 
                                    day = day <= 9 ? "0"+day : day;
                                    var year = currentTime.getFullYear();
                                    return year+"-"+month + "-"+day; 
                                },
                                maxlength: 10
                            },
                            searchoptions: {
                                sopt: ['eq'],
                                dataInit: function (elem) {
                                    $(elem).datepicker({
                                        dateFormat: 'yy-mm-dd',
                                        changeYear: true,
                                        changeMonth: true,                            
                                        showWeek: true,
                                        showButtonPanel: true,
                                        autoclose: false,
                                        currentText: "Clear",
                                        closeText: "Filter",
                                        yearRange: '1999:+1',
                                        onSelect: function( selectedDate, inst ) {
                                            $(this).focus();
                                            var target = $(selectedDate);
                                            var inst = this._getInst(target[0]);
                                            inst.inline = true;
                                            $.datepicker._selectDateOverload(selectedDate, inst);
                                            inst.inline = false;
                                            this._updateDatepicker(inst);
                                        }
                                    }).focus(function() {
                                        var thisCalendar = $(this);
                                        $('.ui-datepicker-close').click(function() {
                                            var selectedDate = $("#gs_kk").val();
                                            setTimeout(function () {
                                                $('#list')[0].triggerToolbar();
                                            }, 100);
    
                                        });
    
                                        $('.ui-datepicker-current').click(function() {
                                            var selectedDate = $("#gs_kk").val('');
                                        });
                                    });
                                }
                            }
                        },
                        { name: "ll", label: "c12", editable: true },
                        { name: "mm", label: "c13", editable: true }
                    ],
                    cmTemplate: { width: 100, autoResizable: true },
                    rowNum: 1000,
                    records: 1000,
                    rownumWidth: 40,
                    rowList: [20, 100, 1000, 10000, "100000:All"],
                    viewrecords: true,
                    rownumbers: true,
                    toppager: false,
                    pager: false,
                    shrinkToFit: false,
                    multiselect: true,
                    editurl: 'clientArray',
                    loadonce: true,
                    width: 800,
                    height: 400,
                    onSortCol: function () {
                        startTime = new Date();
                        measureTime = true;
                    },
                    /*onSelectRow: function (rowid) {
                        var $self = $(this),
                            savedRow = $self.jqGrid("getGridParam", "savedRow");
                        if (savedRow.length > 0) {
                            $self.jqGrid("restoreRow", savedRow[0].id);
                        }
                        $self.jqGrid("editRow", rowid);
                    },*/
                    loadComplete: function () {
                        if (measureTime) {
                            setTimeout(function () {
                                //alert("Total loading time: " + timeInterval + "ms");
                            }, 50);
                            measureTime = false;
                        }
                    },
                    autoencode: true,
                    caption: "Shows the performance of resizing. Make double-click on the column resizer"
                }).jqGrid("filterToolbar", {
                        beforeSearch: function () {
                            startTime = new Date();
                            measureTime = true;
                            return false; // allow filtering
                        }
                }).jqGrid("gridResize");
                $grid.jqGrid("setFrozenColumns");
            });
    
    
             timeInterval = new Date() - startTime;
             setTimeout(function () {
                // alert("Total time: " + timeInterval + "ms");
             }, 50);
    
    
            // START: Sorting even after inline editing
             $.each($('#list')[0].grid.headers, function () {
                var $th = $(this.el), i, l, clickHandler, clickHandlers = [],
                    currentHandlers = $._data($th[0], "events"),
                    clickBinding = currentHandlers.click;
    
                if ($.isArray(clickBinding)) {
                    for (i = 0, l = clickBinding.length; i < l; i++) {
                        clickHandler = clickBinding[i].handler;
                        clickHandlers.push(clickHandler);
                        $th.unbind('click', clickHandler);
                    }
                }
                $th.click(function () {
                    var p = $grid[0].p, savedRow = p.savedRow, j, len = savedRow.length;
                    if (len > 0) {
                        // there are rows in cell editing or inline editing
                        if (p.cellEdit) {
                            // savedRow has the form {id:iRow, ic:iCol, name:nm, v:value}
                            // we can call restoreCell or saveCell
                            //$grid.jqGrid("restoreCell", savedRow[0].id, savedRow[0].ic);
                            $grid.jqGrid("saveCell", savedRow[0].id, savedRow[0].ic);
                        } else {
                            // inline editing
                            for (j = len - 1; j >= 0; j--) {
                                // call restoreRow or saveRow
                                //$grid.jqGrid("restoreRow", savedRow[j].id);
                                $grid.jqGrid("saveRow", savedRow[j].id);
                            }
                        }
                    }
                });
                l = clickHandlers.length;
                if (l > 0) {
                    for (i = 0; i < l; i++) {
                        $th.bind('click', clickHandlers[i]);
                    }
                }
            }); 
            // END: Sorting even after inline editing
    
    
             // On Click Of Button
            $( "#Change_Value" ).click(function() {
                var v = $("#name").val();
                var myGrid = $("#list");
                var selRowIds = myGrid.jqGrid("getGridParam", "selarrrow");
                //alert(selRowId.length);
                for (var i = 0; i < selRowIds.length; i++) {
                    //rowData = myGrid.jqGrid("getLocalRow", selRowIds[i]);
                    // one can uses the data here
                    myGrid.jqGrid("editRow", selRowIds[i], true);
                }
            });
        });
    
        function getStates() {
            var statesAsString = '';
            $.ajax({
                type    : "GET",
                url     : "https://api.myjson.com/bins/xvjhl",
                ContentType : 'json',
                cache: false,
                async: false,
                success : function (data) {
                    var len = data.length;
                    for ( var i = 0; i < len; i++) {
                        if(!(data[i] == null || data[i].toUpperCase() == 'NULL'))
                        {
                            statesAsString += data[i] + ':' + data[i]+ ';';
                        }
                        }   
                        statesAsString = statesAsString.slice(0, -1);               
                }
            })
            return statesAsString;
        }
    //]]>
    </script>
    

    Country:               State:                 

                        <input type="button" name="reset" id="reset" value="Reset" />
                    </TD>
                    <TD align=right>
                        <input type="button" name="Change_Value" id="Change_Value" value="Change Priority to High" /> 
                    </TD>
                </TR>
            </TBODY>
        </TABLE>
    </div>
    
    <div id='gridSearchResult' style="margin-top: 10px;">
        <table id="list"></table>
    </div>
    <div style="border: 1px solid black; align: centre; margin-top: 10px; padding-top: 10px; padding-bottom: 10px;">
        <TABLE width="100%">
        <TBODY>
            <TR>
                <TD align=center>
                    <input type="button" name="save" id="save" value="Save" />&nbsp;&nbsp;
    
                    <input type="button" name="submit" id="submit" value="Submit" />
                </TD>
            </TR>
        </TBODY>
    </TABLE>
    </div>