0

I'm using 4.8.2. I've been trying to utilize the following solution, which displays editable check boxes without needing to select the row first:

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

I looked into using formatoptions : {disabled:false}, but I didn't want to create a custom event handler to handle the checkbox events. jqgrid has the editRow event handler, which works fine when users hit the enter key. I'm trying to find a way to automatically save the user's check box change and do some other processing after the row is saved.

Using the solution liked above, I am able to update the cell and save the row. However, I'm unable to trigger the grid's aftersavefunc event using jQuery("#grid_id").saveRow().

I've included all of my code below. I've added a comment where I'm having the issue. Any help would be much appreciated.

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 = [];
                    }
            });
        }

    }
Michael Sobczak
  • 1,045
  • 1
  • 24
  • 45
  • 1
    See [this](http://stackoverflow.com/questions/32910435/jqgrid-checkbox-editing-not-able-to-edit-selected-row) I had the same problem just 2 days back. Oleg advised me to use `formatoptions : {disabled:false}` but I have used an alternative way too. See the [fiddle](http://jsfiddle.net/HJema/183/) – Dipen Shah Oct 08 '15 at 20:07
  • 1
    Also its important to know what version of jqGrid you use. If possible provide a fiddle which will give a perfect mvce example – Dipen Shah Oct 08 '15 at 20:08
  • @DipenShah thanks for referring to your question! One difference between what I'm trying to do and what you're doing is that I need to save the original state of the checkbox and compare it to the new checkbox state. Also, I'm sending all of the checkbox updates to the server in one batch, when the user either pages through the grid or clicks on a custom [save edits] button. I'll need to see how I would nee to change things around to not use the inline editing events and instead trigger everything off of the checkbox change itself. – Michael Sobczak Oct 08 '15 at 20:25
  • You can probably use the jqGrid's `onPaging` event to send the data to the server in a batch. Also in my real application, I have a select all button which acts similar to your [save edits] button. With minor modifications I think you can use the code given in the answer. – Dipen Shah Oct 08 '15 at 20:40
  • @DipenShah I need to see if I can incorporate what Oleg provided to you with the grid I'm working on. Similar to you, I need to use inline editing. However, I'm using it to determine the before and after value of the checkbox and save the change in a JavaScript array in the page. – Michael Sobczak Oct 09 '15 at 16:41

0 Answers0