jqGrid how to center the Delete dialog when using

2019-08-30 06:16发布

问题:

I'm using jqGrid formatter action with a long grid, I'm trying to position the delete dialog in the center of the screen, I did that already but for some reason the window scrolls to the top of the grid and the dialog becomes invisible to the user

Click here for a screencast of the issue

Here's the code used:

    // define handler function for 'afterSubmit' event.
    var actionStatus = function(response,postdata){
    //alert($.parseJSON(response.responseText).USERDATA.MSG);
    aData = $.parseJSON(response.responseText).USERDATA;

    if (aData.STATUS){
        $.jgrid.info_dialog("Success", aData.MSG, $.jgrid.edit.bClose,{buttonalign:'right'});
        var thisId = aData.ID;
        $("#list").jqGrid('setGridParam',{loadComplete: function(){$(this).jqGrid('setRowData', thisId, false, 'mybold'); $("#" + thisId).effect("highlight", {color:"orange" }, 3000);}});
    }
    else {
        $(".topinfo").html(aData.MSG);
    }
    return [aData.STATUS, aData.MSG, aData.ID];
}

$(document).ready(function(){

    var grid = $("#list");
    var lastSel;
    var selICol; //iCol of selected cell
    var selIRow; //iRow of selected cell

    $("#list").jqGrid({
        url:'data.cfc?method=GetRecords', //CFC that will return the users
        datatype: 'json', //We specify that the datatype we will be using will be JSON
        //The JSON reader. This defines what the JSON data returned from the CFC should look like
        jsonReader: {
                      root: "DATA",
                      page: "CURPAGE",
                      total: "TOTALPAGES",
                      records: "TOTALROWS",
                      repeatitems: false,
                      id: ""
              },
        colNames: [ "YEAR", "SPC_CD", "SPC_CD", "BASE_COUNT", "BASE_MEDIAN", "START_COUNT", "START_MEDIAN", " "],
        /*
        If you want not display some columns which you need only to build the composite key you can use for this columns following options in the colModel
            hidden: true, editable: true, editrules: { edithidden: false }, hidedlg: true
        It will make columns invisible for user, but the data will be send to server at all edit operations.
        */
        colModel: [
            { name: "year", sortable: true, index:'year', editable: false, editoptions:{size:5, maxlength:4}, editrules:{required:true, integer:true}
            //, formoptions:{elmsuffix:" <img src='images/red_asterisk.gif' title='Required'>"} 
            },
            { name: "spc_cd", sortable: true, index:'spc_cd', editable: false, editoptions:{size:13, maxlength:10}, editrules:{required:true}
            //, formoptions:{ elmsuffix:" <img src='images/red_asterisk.gif' title='Required'>"} 
            },
            { name: "spc_cd", sortable: true, index:'spc_cd', editable: true, editoptions:{size:13, maxlength:10} },
            { name: "base_count", sortable: true, index:'base_count', editable: true, editoptions:{size:13, maxlength:10}, editrules:{integer:true} },
            { name: "base_median", sortable: true, index:'base_median', editable: true, editoptions:{size:13, maxlength:10}, editrules:{integer:true} },
            { name: "start_count", sortable: true, index:'start_count', editable: true, editoptions:{size:13, maxlength:10}, editrules:{integer:true} },
            { name: "start_median", sortable: true, index:'start_median', editable: true, editoptions:{size:13, maxlength:10}, editrules:{integer:true} 
                /*
                ,editOptions:{  dataEvents: [
                                    {
                                        type: 'keydown',
                                        fn: function (e) {
                                            var key = e.charCode || e.keyCode;
                                            if (key == 9)//tab
                                            {
                                                //Enter edit row for next row in grid
                                               // $('#list').jqGrid().editCell(" + selIRow + " + 1, " + selICol + ", true);
                                                $('#list').jqGrid("editCell", iRow+1, iCol, true)
                                            }
                                        }
                                    }
                                ]                                               
                }
                */
            },
            { name: 'myac', width:60, fixed:true, sortable:false, resize:false, formatter:'actions', 
                formatoptions:{ keys:true
                                , editformbutton:false, 
                                editbutton : false, 
                                // For multi-column keys, we need to pass additional data to the delete function
                                delOptions:{ url:"data.cfc?method=delRecord", reloadAfterSubmit:true, closeOnEscape:true, afterSubmit: actionStatus, 
                                                serializeDelData: function (postdata) {
                                                    var rowdata = $('#list').getRowData(postdata.id);
                                                    // append postdata with any information 
                                                    //return {id: postdata.id, oper: postdata.oper, year: rowdata.year, spc_cd: rowdata.spc_cd};
                                                    postdata.year = rowdata.year;
                                                    postdata.spc_cd = rowdata.spc_cd;
                                                    return postdata;
                                                }, 
                                                recreateForm: true,
                                                beforeShowForm: function ($form) {
                                                    //var sel_id = $("#list").jqGrid('getGridParam', 'selrow');
                                                    //$("td.delmsg", $form[0]).html("Delete record with <b>id=" + $("#list").jqGrid('getCell', sel_id, 'spc_cd') + "</b>?");

                                                    var idOfDeletedRow = $("#DelData>td:first").text();
                                                    $("td.delmsg", $form[0]).html( "Delete record with <br><b>year=" +
                                                            $("#list").jqGrid('getCell', idOfDeletedRow, 'year') + "</b> and <b>spc_cd=" +
                                                            $("#list").jqGrid('getCell', idOfDeletedRow, 'spc_cd') + "</b> ?" );


                                                    //$("#delmod" + grid[0].id).addClass("centered");
                                                    var delDiv = $("#delmod" + grid[0].id);
                                                    delDiv.center();

                                                    //var scrollPosition = $("#list").closest(".ui-jqgrid-bdiv").scrollTop();
                                  // alert(scrollPosition);
                                   //selRowCoordinates = $('#'+selRowId).offset();
                              // delDiv.scrollTop(scrollPosition);

                                                    //var gviewHeight = $("#gview_" + $.jgrid.jqID(this.id)).outerHeight();
                                                    //delDiv.css({top:'50%',left:'50%',margin:'-'+(delDiv.height() / 2)+'px 0 0 -'+(delDiv.width() / 2)+'px'});
                                                }
                                                /*
                                                ,
                                                afterShowForm: function($form) {
                                    var $dialog = $form.closest('div.ui-jqdialog'),
                                        idOfDeletedRow = $("#DelData>td:first").text(),
                                        selRowCoordinates = $('#'+idOfDeletedRow).offset();

                                    $form.find("td.delmsg:first")
                                        .html("Delete record with <b>code=" +
                                            $("#list").jqGrid('getCell', idOfDeletedRow, 'cd') + "</b>?");
                                    $dialog.offset(selRowCoordinates);

                                        }
                                        */
                                }
                               /*
                               , 
                                editOptions:{ url:"data.cfc?method=editRecord", reloadAfterSubmit:true, closeOnEscape:true, closeAfterEdit:true, afterSubmit: actionStatus
                                                , serializeEditData: function (postdata) {
                                                    var rowdata = $('#list').getRowData(postdata.id);
                                                    // append postdata with any information 
                                                    postdata.old_year = rowdata.year;
                                                    postdata.old_spc_cd = rowdata.spc_cd;
                                                    return postdata;
                                                }                                               
                                }
                                */ 
                } 
            }
        ],
        afterEditCell: function(rowid, cellname, value, iRow, iCol) {

            // Get a handle to the actual input field
            var inputControl = $('#' + (iRow) + '_' + cellname);

            // Listen for tab on col #7 START_MEDIAN, which is the last editable column in the row
            // as we need to move to the first editable cell in the next row
            if ( iCol == 7 ){
                inputControl.bind("keydown",function(e) {               
                    if (e.charCode || e.keyCode === 9) {  // Enter key:

                        var increment = 1;
                        // Do not go out of bounds
                        var lastRowInd = $("#list").jqGrid("getGridParam","reccount");
                        if ( iRow+increment == 0 || iRow+increment == lastRowInd+1)
                            return;   // we could re-edit current cell or wrap
                        else
                            $("#list").jqGrid("editCell", iRow+increment, 3, true); //move to the first editable cell (#3) in the next row
                    }
                });
            } // End keydown binding
        },
        beforeEditCell : function(rowid, cellname, value, iRow, iCol){
            selICol = iCol;
            selIRow = iRow;
        },
        /*
        onSelectRow: function(id) {
                    if (id && id !== lastSel) {
                        $("#list").jqGrid('restoreRow',lastSel);
                        lastSel = id;
                    }
                },
                ondblClickRow: function(id, ri, ci) {
                    $("#list").jqGrid('editRow',id,true);
                    return;
                },
        */
        cellEdit : true,
        cellsubmit : 'clientArray',
        onPaging : isDataChanged,
        hidegrid: false,
        shrinkToFit: true,
        altRows: true,
        toppager: true,
        gridview: true, //speed the reading process for large data sets
        ignoreCase: true, //when sorting
        pager: $('#pager'), //The div we have specified, tells jqGrid where to put the pager
        rowNum:100, //Number of records we want to show per page
        //rowList:[20,50], //Row List, to allow user to select how many rows they want to see per page
        rowTotal: 1000, // get this number of rows from the server
        //loadonce:true, //load all the needed data from server at once and then operate on it locally
        sortorder: "desc", //Default sort order
        sortname: "year,spc_cd", //Default sort column
        //viewsortcols: true, // view sortable columns
        viewrecords: true, //Shows the nice message on the pager
        //imgpath: '/Test/themes/basic/images', //Image path for prev/next etc images
        caption: 'Table: DATA_TEST', //Grid Name
        recordtext: "Record {0} - {1} of {2}",//Pager information to show
        rownumbers: true,//Show row numbers
        rownumWidth: "40",//Width of the row numbers column
        sortable: true,
        width: 'auto',
        height:'auto', //I like auto, so there is no blank space between. Using a fixed height can mean either a scrollbar or a blank space before the pager
        mtype:'POST',   
        //toolbar:[true,"top"], //Shows the toolbar at the top. We will use it to display user feedback
        //editurl:"data.cfc?method=editRecord" //The Add/Edit function call
        //editurl: 'clientArray',
        }

    );

    $("#list").jqGrid(
        'navGrid',
        '#list_toppager', //The id of the top pager is a combination of grid id and “_toppager”
        {addicon:"ui-icon-circle-plus", addtext:"Add New Record&nbsp;&nbsp;&nbsp;", addtitle:"", del:false, edit:false, search:false, closeOnEscape:true}, //options 
        {}, //edit options
        {url:"data.cfc?method=addRecord", reloadAfterSubmit:true, closeAfterAdd: true, afterSubmit: actionStatus, 
            // make the primary key columns editable in add mode
            beforeInitData: function(formid) {
                $("#list").jqGrid('setColProp','year',{editable:true});
                $("#list").jqGrid('setColProp','spc_cd',{editable:true});
            },
            // after the form is shown, revert the primary key columns to un-editable
            afterShowForm: function (formid) {
                $("#list").jqGrid('setColProp','year',{editable:false});
                $("#list").jqGrid('setColProp','spc_cd',{editable:false});
            }
        }, // add options 
        {}, // del options
        {}, // search options
        {closeOnEscape:true}
    ); //.navSeparatorAdd('#list_toppager');

    $("#list").jqGrid().navGrid().navButtonAdd('#list_toppager',
            {
                caption: "Save Changed Rows&nbsp;&nbsp;&nbsp;",
                buttonicon: "ui-icon-disk",
                onClickButton: function () {
                    $("#list").jqGrid("restoreCell", selIRow, selICol, true); //if there's an open cell, first restore it
                    var ret = $("#list").getChangedCells('all');
                    //console.dir(ret);
                    //console.info($('#1_base_count').val());
                    var ret2 = JSON.stringify(ret);
                    //console.info(ret2);
                    $.ajax({
                        type: "post",
                        url: "data.cfc?method=editRecord",
                        data: { jsonData: ret2 },
                        // contentType: "application/json",
                        //dataType: "json",
                        success: function(data) {
                            $.jgrid.info_dialog("Success", "Rows Updated Successfully", $.jgrid.edit.bClose,{buttonalign:'right'});
                            /*
                            $('<div></div>').html(data).dialog({
                                'title' : 'Message',
                                'modal' : true,
                                'width' : 400,
                                'height' : 400,
                                'buttons' : {
                                    'OK' : function() {
                                        $(this).dialog('close');
                                    }
                                }
                            });
                            */
                            $('#list').trigger('reloadGrid');
                        },
                        error: function(){
                            $.jgrid.info_dialog("Error", "Error Occurred while saving data", $.jgrid.edit.bClose,{buttonalign:'right'});
                        }
                    });
                },
                position: "first"
            }
            ); //.navSeparatorAdd('#list_toppager');



//Supresss jqGrid error dialog, called #info_dialog
            /*
            $("#delmodlist").live("focus", function () {

                var errorMessage = $("#delmsg").text();
                $("#delmodlist").center();
                $("#delmodlist").blur();


            });
            */
    //$("#list").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});

    //$("#list_toppager_center").hide();    

});
// define handler function for 'afterSubmit' event.
var actionStatus = function(response,postdata){
aData = $.parseJSON(response.responseText).USERDATA;

    if (aData.STATUS){
        $.jgrid.info_dialog("Success", aData.MSG, $.jgrid.edit.bClose,{buttonalign:'right'});
    else {
        $(".topinfo").html(aData.MSG);
    }
    return [aData.STATUS, aData.MSG, aData.ID];
}

$(document).ready(function(){

    var grid = $("#list");
    var lastSel;
    var selICol; //iCol of selected cell
    var selIRow; //iRow of selected cell

    $("#list").jqGrid({
        url:'data.cfc?method=GetRecords', //CFC that will return the users
        datatype: 'json', //We specify that the datatype we will be using will be JSON
        //The JSON reader. This defines what the JSON data returned from the CFC should look like
        jsonReader: {
                      root: "DATA",
                      page: "CURPAGE",
                      total: "TOTALPAGES",
                      records: "TOTALROWS",
                      repeatitems: false,
                      id: ""
              },
        colNames: [ "YEAR", "CD", "SPC_CD", "BASE_COUNT", "BASE_MEDIAN", "START_COUNT", "START_MEDIAN", " "],
        /*
        If you want not display some columns which you need only to build the composite key you can use for this columns following options in the colModel
            hidden: true, editable: true, editrules: { edithidden: false }, hidedlg: true
        It will make columns invisible for user, but the data will be send to server at all edit operations.
        */
        colModel: [
            { name: "year", sortable: true, index:'year', editable: false, editoptions:{size:5, maxlength:4}, editrules:{required:true, integer:true}
            //, formoptions:{elmsuffix:" <img src='images/red_asterisk.gif' title='Required'>"} 
            },
            { name: "cd", sortable: true, index:'cd', editable: false, editoptions:{size:13, maxlength:10}, editrules:{required:true}
            //, formoptions:{ elmsuffix:" <img src='images/red_asterisk.gif' title='Required'>"} 
            },
            { name: "spc_cd", sortable: true, index:'spc_cd', editable: true, editoptions:{size:13, maxlength:10} },
            { name: "base_count", sortable: true, index:'base_count', editable: true, editoptions:{size:13, maxlength:10}, editrules:{integer:true} },
            { name: "base_median", sortable: true, index:'base_median', editable: true, editoptions:{size:13, maxlength:10}, editrules:{integer:true} },
            { name: "start_count", sortable: true, index:'start_count', editable: true, editoptions:{size:13, maxlength:10}, editrules:{integer:true} },
            { name: "start_median", sortable: true, index:'start_median', editable: true, editoptions:{size:13, maxlength:10}, editrules:{integer:true} 
                /*
                ,editOptions:{  dataEvents: [
                                    {
                                        type: 'keydown',
                                        fn: function (e) {
                                            var key = e.charCode || e.keyCode;
                                            if (key == 9)//tab
                                            {
                                                //Enter edit row for next row in grid
                                               // $('#list').jqGrid().editCell(" + selIRow + " + 1, " + selICol + ", true);
                                                $('#list').jqGrid("editCell", iRow+1, iCol, true)
                                            }
                                        }
                                    }
                                ]                                               
                }
                */
            },
            { name: 'myac', width:60, fixed:true, sortable:false, resize:false, formatter:'actions', 
                formatoptions:{ keys:true
                                , editformbutton:false, 
                                editbutton : false, 
                                // For multi-column keys, we need to pass additional data to the delete function
                                delOptions:{ url:"data.cfc?method=delRecord", reloadAfterSubmit:true, closeOnEscape:true, afterSubmit: actionStatus, 
                                                serializeDelData: function (postdata) {
                                                    var rowdata = $('#list').getRowData(postdata.id);
                                                    // append postdata with any information 
                                                    //return {id: postdata.id, oper: postdata.oper, year: rowdata.year, cd: rowdata.cd};
                                                    postdata.year = rowdata.year;
                                                    postdata.cd = rowdata.cd;
                                                    return postdata;
                                                }, 
                                                recreateForm: true,
                                                beforeShowForm: function ($form) {
                                                                        var idOfDeletedRow = $("#DelData>td:first").text();
                                                    $("td.delmsg", $form[0]).html( "Delete record with <br><b>year=" +
                                                            $("#list").jqGrid('getCell', idOfDeletedRow, 'year') + "</b> and <b>spc_cd=" +
                                                            $("#list").jqGrid('getCell', idOfDeletedRow, 'spc_cd') + "</b> ?" );


                                                    var delDiv = $("#delmod" + grid[0].id);
                                                    //delDiv.center();

                                                        }
                                                /*
                                                ,
                                                afterShowForm: function($form) {
                                    var $dialog = $form.closest('div.ui-jqdialog'),
                                        idOfDeletedRow = $("#DelData>td:first").text(),
                                        selRowCoordinates = $('#'+idOfDeletedRow).offset();

                                    $form.find("td.delmsg:first")
                                        .html("Delete record with <b>code=" +
                                            $("#list").jqGrid('getCell', idOfDeletedRow, 'cd') + "</b>?");
                                    $dialog.offset(selRowCoordinates);

                                        }
                                        */
                                }

                } 
            }
        ],
        afterEditCell: function(rowid, cellname, value, iRow, iCol) {

            // Get a handle to the actual input field
            var inputControl = $('#' + (iRow) + '_' + cellname);

            // Listen for tab on col #7 START_MEDIAN, which is the last editable column in the row
            // as we need to move to the first editable cell in the next row
            if ( iCol == 7 ){
                inputControl.bind("keydown",function(e) {               
                    if (e.charCode || e.keyCode === 9) {  // Enter key:

                        var increment = 1;
                        // Do not go out of bounds
                        var lastRowInd = $("#list").jqGrid("getGridParam","reccount");
                        if ( iRow+increment == 0 || iRow+increment == lastRowInd+1)
                            return;   // we could re-edit current cell or wrap
                        else
                            $("#list").jqGrid("editCell", iRow+increment, 3, true); //move to the first editable cell (#3) in the next row
                    }
                });
            } // End keydown binding
        },
        beforeEditCell : function(rowid, cellname, value, iRow, iCol){
            selICol = iCol;
            selIRow = iRow;
        },

        cellEdit : true,
        cellsubmit : 'clientArray',
        onPaging : isDataChanged,
        hidegrid: false,
        shrinkToFit: true,
        altRows: true,
        toppager: true,
        gridview: true, //speed the reading process for large data sets
        ignoreCase: true, //when sorting
        pager: $('#pager'), //The div we have specified, tells jqGrid where to put the pager
        rowNum:100, //Number of records we want to show per page
        rowTotal: 1000, // get this number of rows from the server
        sortorder: "desc", //Default sort order
        sortname: "year,spc_cd", //Default sort column
        viewrecords: true, //Shows the nice message on the pager

        caption: 'Table: DATA_TEST', //Grid Name
        recordtext: "Record {0} - {1} of {2}",//Pager information to show
        rownumbers: true,//Show row numbers
        rownumWidth: "40",//Width of the row numbers column
        sortable: true,
        width: 'auto',
        height:'auto', //I like auto, so there is no blank space between. Using a fixed height can mean either a scrollbar or a blank space before the pager
        mtype:'POST'
        }

    );

    $("#list").jqGrid(
        'navGrid',
        '#list_toppager', //The id of the top pager is a combination of grid id and “_toppager”
        {addicon:"ui-icon-circle-plus", addtext:"Add New Record&nbsp;&nbsp;&nbsp;", addtitle:"", del:false, edit:false, search:false, closeOnEscape:true}, //options 
        {}, //edit options
        {url:"data.cfc?method=addRecord", reloadAfterSubmit:true, closeAfterAdd: true, afterSubmit: actionStatus, 
            // make the primary key columns editable in add mode
            beforeInitData: function(formid) {
                $("#list").jqGrid('setColProp','year',{editable:true});
                $("#list").jqGrid('setColProp','cd',{editable:true});
            },
            // after the form is shown, revert the primary key columns to un-editable
            afterShowForm: function (formid) {
                $("#list").jqGrid('setColProp','year',{editable:false});
                $("#list").jqGrid('setColProp','cd',{editable:false});
            }
        }, // add options 
        {}, // del options
        {}, // search options
        {closeOnEscape:true}
    ); //.navSeparatorAdd('#list_toppager');

    $("#list").jqGrid().navGrid().navButtonAdd('#list_toppager',
            {
                caption: "Save Changed Rows&nbsp;&nbsp;&nbsp;",
                buttonicon: "ui-icon-disk",
                onClickButton: function () {
                    $("#list").jqGrid("restoreCell", selIRow, selICol, true); //if there's an open cell, first restore it
                    var ret = $("#list").getChangedCells('all');
                    //console.dir(ret);
                    //console.info($('#1_base_count').val());
                    var ret2 = JSON.stringify(ret);
                    //console.info(ret2);
                    $.ajax({
                        type: "post",
                        url: "data.cfc?method=editRecord",
                        data: { jsonData: ret2 },
                        // contentType: "application/json",
                        //dataType: "json",
                        success: function(data) {
                            $.jgrid.info_dialog("Success", "Rows Updated Successfully", $.jgrid.edit.bClose,{buttonalign:'right'});

                            $('#list').trigger('reloadGrid');
                        },
                        error: function(){
                            $.jgrid.info_dialog("Error", "Error Occurred while saving data", $.jgrid.edit.bClose,{buttonalign:'right'});
                        }
                    });
                },
                position: "first"
            }
            ); 



});

回答1:

You don't posted the code of center method which you use or describe which plugin you use. In any way I think that you should use delDiv.center(); inside of afterShowForm and not inside of beforeShowForm.

Like you can see on the demo the problem with scrolling should not exist in general.