jqgrid: working with editable checkboxes

321
November 22, 2016, at 10:29 AM

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 = [];
                    }
            });
        }
    }
READ ALSO
fullCalendar Orientation - Views

fullCalendar Orientation - Views

Does anyone have an idea how to manipulate with the orientation days and hours. For example I want my calendar looks like:full calendar.

143
Sticky nav not smooth when bg added

Sticky nav not smooth when bg added

I've been trying to do a sticky navigation that first has a absolute position at bottom, but when the user scrolls 100vh the sticky nav sticks at the top as a fixed position. .

162
How to make parent node in treeview checked if only one from its child nodes checked , and unchecked if all child nodes unchecked too

How to make parent node in treeview checked if only one from its child nodes checked , and unchecked if all child nodes unchecked too

How to make parent node in treeview checked if only one from its child nodes checked , and unchecked if all child nodes unchecked too. .

201
Assign value to Knockout observable?

Assign value to Knockout observable?

I have a page that populates its fields(dropdowns and textboxes) from the DB when the page loads via VIEWDATA object from controller. .

300