jqgrid:使用可编辑的复选框

时间:2015-10-08 20:02:36

标签: jquery jqgrid

我使用的是4.8.2。我一直在尝试使用以下解决方案,该解决方案显示可编辑的复选框,而无需先选择行:

http://wraithnath.blogspot.com/2012/01/how-to-have-editable-checkbox-column-in.html

我研究过使用formatoptions : {disabled:false},但我不想创建自定义事件处理程序来处理复选框事件。 jqgrid有editRow事件处理程序,当用户点击回车键时它可以正常工作。我试图找到一种方法来自动保存用户的复选框更改,并在保存行后执行其他处理。

使用上面提到的解决方案,我可以更新单元格并保存行。但是,我无法使用aftersavefunc触发网格的jQuery("#grid_id").saveRow()事件。

我已在下面提供了所有代码。我已经在我遇到问题的地方添加了评论。任何帮助将不胜感激。

var j$ = jQuery.noConflict();

var savedRows = [];

function updateRows(id, origIsSelected, savedIsSelected)
{
    var found = false;

    /*
        Check the array for the presence of the row.
        If it is found, add the saved value.
    */
    for (var index = 0; index < savedRows.length; index++) {
        if(savedRows[index].id == id) {
            savedRows[index].savedIsSelected = savedIsSelected;

            if (savedIsSelected == '1')
                savedRows[index].value = true;
            else
                savedRows[index].value = false;

            found = true;
        }
    }

    /*
        If row not found, it must be new.
    */
    if (found == false) {
        var i = savedRows.length;
        savedRows[i] = {};
        savedRows[i].id = id;
        savedRows[i].origIsSelected = origIsSelected;
        savedRows[i].savedIsSelected = savedIsSelected;

        if (savedIsSelected == '1')
            savedRows[i].value = true;
        else
            savedRows[i].value = false;

    }
}

j$.urlParam = function(name, url) {
    if (!url) {
     url = window.location.href;
    }
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
    if (!results) { 
        return undefined;
    }
    return results[1] || undefined;
}

var colModel = [
                    { label: 'Site ID', name: 'siteId', width: 75, 
                      sortable: false,
                      editable: true, 
                      hidden: true,
                      editrules: { edithidden: true }
                     },

                     { label: 'Common MBU ID', name: 'commonMbuId', width: 75, 
                       sortable: false,
                       editable: true, 
                       hidden: true,
                       editrules: { edithidden: true }
                     },

                     { label: 'Include', name: 'isSelected', width: 50,
                       sortable: false,
                       formatter: checkboxFormatter, 
                       unformat: unformatCheckbox, 
                       editable: true, 
                       edittype: "checkbox", 
                       editOptions: {value:"1:0"}, 
                       align: 'center' },

                     { label: "Geo", name:"geocode", width:50,
                       sortable: false,
                       align: 'center' },

                     { label: 'Distr. Qty', name: 'distribution', width: 40,
                       sortable: false,
                       formatter : 'number',
                       formatoptions: { thousandsSeparator: ",", decimalPlaces: 0 },
                       align: 'right' },

                      { label: 'Distance', name: 'distance', width: 60,
                        sortable: false,
                        formatter : 'number',
                        formatoptions: { thousandsSeparator: ",", decimalPlaces: 2 },
                        align: 'right'
                      },

                     { label: 'Investment', name: 'investment', width: 70, 
                       sortable: false,
                       formatter : 'currency',
                       formatoptions:{decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, prefix: "$ "},
                       align: 'right'
                     },

                ];

j$(document).ready(function () {

    var lastSelection;

    var mediaPlanId = '5075';
    var siteId = '11748878';
    var wrapZoneId = '';
    var productCode = 'INS_SHARED';

    j$("#jqGrid").jqGrid({

        datatype: function(postdata) {

            j$('#' + 'load_' + 'jqGrid').show();

            saveChanges();

            var rows = '' + postdata.rows;
            var page = '' + postdata.page;
            var sidx = postdata.sidx;
            var sord = postdata.sord;

            var pageSize = '' + postdata.rows;

                j$.ajax({
                    async: false,
                    url: "servlet/mediaPlanGeoDetailNonWrapServlet",
                    type: 'GET',
                    dataType: 'json',
                    data: {"mediaPlanId" : mediaPlanId, "productCd" : productCode, "siteId" : siteId, "page" : page, "rows" : rows },
                    cache: false,
                    contentType: 'application/json',
                    error: function(jqXHR, textStatus, errorThrown) {
                        var msg = 'textStatus = ' + textStatus + 
                            'errorThrown = ' + errorThrown;
                        alert ( msg ); 
                        },
                    success: function(data, textStatus, jqXHR) {

                        //var json = j$.parseJSON(data);
                        var json = data;

                        var thisGridId = "#jqGrid";

                        for (var i = 0; i < json.rows.length; i++) {
                            /*
                                custom formatter for the checkbox field is causing issues with the save event.
                                For now, convert from 1:0 to Yes:No. 
                                This needs to be converted back when changes are sent to the server.
                            */

                            if (json.rows[i].isSelected == 1)
                                json.rows[i].isSelected = '1';
                            else
                                json.rows[i].isSelected = '0';
                        }

                        var thegrid = j$(thisGridId)[0];
                        thegrid.addJSONData(json);

                        j$('#' + 'load_' + 'jqGrid').hide();
                    }

                });

        },

          editurl: 'clientArray',
            page: 1, 

            colModel: colModel,

            onSelectRow: function (rowid) {
                var grid = j$(this);

                if (rowid && rowid !== lastSelection) {
                    grid.jqGrid('restoreRow', lastSelection);
                    lastSelection = rowid;
                }

                var origIsSelected = grid.jqGrid('getCell', lastSelection, 'isSelected');

                grid.jqGrid('editRow', lastSelection, {keys: true, 
                        url: 'clientArray',
                        aftersavefunc: function (rowid, jqXHR, savedData) {
                            if (savedData.isSelected !== origIsSelected) {

                                var row = grid.getRowData(rowid);

                                // Save changes to local array
                                var commonMbuId = grid.jqGrid('getCell', rowid, 'commonMbuId');
                                updateRows(commonMbuId, origIsSelected, savedData.isSelected);

                                j$(this).jqGrid("resetSelection");
                            }

                        }
                    }

                );

            },

    shrinkToFit: false,
    viewrecords: true,
    height: '100%',
    rowNum: 20,
    pager: "#jqGridPager"

});

});

    function checkboxFormatter(cellvalue, options, rowObject) {
        var html = '';

        var checkboxnameid = options.colModel.name + options.rowId;

        var onclick = 'onclick="selectTemplateLine(\'' + options.gid + '\', \'' + options.rowId + '\', \'' + checkboxnameid + '\');" ';

        if (cellvalue == true || cellvalue == "1")
        {
            html = '<input type="checkbox" id="' + checkboxnameid + '"checked="checked" ' + onclick + ' />';
        }
        else
        {
            html = '<input type="checkbox" id="' + checkboxnameid + '" ' + onclick + ' />';
        }

        return html;
    }

    function  unformatCheckbox (cellvalue, options)
    {
        if(cellvalue.indexOf('checked') > -1)
            return '1';
        else
            return '0';
    }

    function selectTemplateLine(gid, rowId, checkboxnameid)
    {
        var checkedValue = j$('#' + checkboxnameid).is(':checked') ? '1' : '0';

        var grid = j$('#' + gid);

        var rowids = grid.getDataIDs();

        for (var i = 0; i < rowids.length; i++) {

            if (rowId == rowids[i]) {

                j$('#' + gid).jqGrid('setSelection', rowId);

                j$('#' + gid).editRow(rowId);

                j$('#' + gid).jqGrid('editCell', i+1, true);
                j$('#' + gid).jqGrid('setCell', i+1, 'isSelected', checkedValue);
                j$('#' + gid).jqGrid('saveCell', i+1, true);  // This is working

                j$('#' + gid).saveRow(rowId);  // <- does not trigger aftersafefunc

                var row = j$('#' + gid).getRowData(rowId);

                j$('#' + gid).jqGrid("resetSelection");
            }
        }

        return true;
    }

    function saveChanges() {

        var changesToSend = [];

        if(savedRows.length > 0 ) {

            for(var i = 0; i < savedRows.length; i++) {

                if ( savedRows[i].origIsSelected != savedRows[i].savedIsSelected )
                {
                    var i = changesToSend.length;
                    changesToSend[i] = {};
                    changesToSend[i].id = Number(savedRows[i].id);
                    changesToSend[i].value = savedRows[i].value;
                }   

            }

        }

        if (changesToSend.length > 0)
        {
            var jsonPayload = JSON.stringify(changesToSend);

            $.ajax({
                async: false,
                url: "servlet/setSelected",
                type: 'POST',
                dataType: 'json',
                data: jsonPayload,
                contentType: 'application/json',
                error: function(jqXHR, textStatus, errorThrown) {
                    var msg = 'textStatus = ' + textStatus + 
                        'errorThrown = ' + errorThrown;
                    alert ( msg );
                    },
                success: function(data, textStatus, jqXHR) { 
                    var msg = 'textStatus = ' + textStatus;
                    alert ( msg );

                    savedRows = [];
                    }
            });
        }

    }

0 个答案:

没有答案