2

I know how to use a custom formatter and call a JavaScript function in jqGrid. I also know that I can use gridComplete function to bind a jQuery event. My question is similar to the following – but not the same. Custom formatter in jqGrid which calls jQuery function

Okay, in the approach mentioned in the above question, we can use a jQuery function on the click event of the element returned by the formatter – but it required looping through all the rows.

Is there a better way to get the current row value into a jQuery event handler without looping, in jqGrid?

Note: Please note that I need to invoke a jQuery event handler which will process current row value – not a simple javascript function.

My code is listed below.

<script type="text/javascript">
    function clickme(rowID) {
        alert("hi");
    }
    $(document).ready(function() {
        $("#grid").jqGrid({
            url: "GamesList.aspx/GetMyGames",
            mtype: 'POST',
            postData: {
                gameSearch: $('#txtGameName').val(),
                ownerSearch: $('#txtOwner').val(),
                createdDateFrom: $('#txtCreatedFrom').val(),
                createdDateTo: $('#txtCreatedTo').val(),
                liquidAmountFrom: $('#txtLmiquidAmountFrom').val(),
                liquidAmountTo: $('#txtLmiquidAmountTo').val()
            },
            datatype: "local", //json if want to load initially
            ajaxGridOptions: {
                contentType: 'application/json; charset=utf-8'
            },
            serializeGridData: function(postData) {
                return JSON.stringify(postData);
            },
            jsonReader: {
                repeatitems: false,
                root: function(obj) {
                    return obj.d;
                }
            },
            colNames: ['GameID', 'GameName', 'GameOwner', 'PlannedCloseDate', 'CreatedOnDate', 'GameLiquidAmount', 'Join'],
            colModel: [{
                name: 'GameID',
                index: 'GameID'
            }, {
                name: 'GameName',
                index: 'GameName'
            }, {
                name: 'GameOwner',
                index: 'GameOwner'
            }, {
                name: 'PlannedCloseDate',
                index: 'PlannedCloseDate',
                formatter: 'date',
                formatoptions: {
                    srcformat: 'm/d/Y',
                    newformat: 'm/d/Y'
                }
            }, {
                name: 'CreatedOnDate',
                index: 'CreatedOnDate',
                formatter: 'date',
                formatoptions: {
                    srcformat: 'm/d/Y',
                    newformat: 'm/d/Y'
                }
            }, {
                name: 'GameLiquidAmount',
                index: 'GameLiquidAmount'
            }, {
                name: 'Join',
                index: 'GameID',
                width: 30,
                formatter: function(cellvalue, options, rowObject) {
                    return '<span class="ui-icon ui-icon-folder-open app-custom-button-join"  title="click to open" onclick="clickme(' + options.rowId + ') ;"></span>';
                }
            }],
            rowNum: 10,
            /*rowList: [10, 20, 30],*/
            pager: '#pager2',
            sortname: 'id',
            viewrecords: true,
            sortorder: "desc",
            caption: "Games",
            gridview: true,
            height: "auto",
            loadonce: true,
            recordtext: "Records {0} - {1} of {2}",
            emptyrecords: "No records to view",
            loadtext: "Loading...",
            pgtext: "Page {0} of {1}",
            gridComplete: function() {
                //Assign a click event to custom button [after gridComplete]
                $(".app-custom-button-join").click(function() {
                    alert("HELLO");
                });
            }
        });
        $("#btnSearch").click(function(e) {
            $("#grid").jqGrid('setGridParam', {
                datatype: 'json'
            }).trigger('reloadGrid');
            e.preventDefault();
        });
    });
</script>

References:

  1. jqgrid custom formatter button click event not working
  2. jqGrid gridComplete:- getRowData - get row cell value from array
  3. Issue with jqGrid and jquery click event
  4. Custom formatter in jqGrid which calls jQuery function
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418

2 Answers2

2

You are right. Your current code bind separate (multiple) click handler for every span.app-custom-button-join of the column Join. To make the code more effective one can register one click handler on the whole grid. The standard event processing makes bubbling (from inner to outer). jqGrid registers already one click handler and it has beforeSelectRow and onCellSelect which will be called inside of the click handler. Thus you can replace gridComplete with more effective code of beforeSelectRow callback for example. The corresponding implementation can looks like below

beforeSelectRow: function (rowid, e) {
    var $self = $(this),
        $td = $(e.target).closest("tr.jqgrow>td"),
        rowid = $td.parent().attr("id"),
        rowData = $self.jqGrid("getLocalRow", rowid),
        // or rowData = $self.jqGrid("getRowData", rowid)
        iCol = $td.length > 0 ? $td[0].cellIndex : -1,
        colModel = $self.jqGrid("getGridParam", "colModel");
    if (iCol >= 0 && colModel[iCol].name === "Join" &&
            $(e.target).hasClass("app-custom-button-join")) {
        alert("HELLO");
        return false;
    }

    return true;
}

The above code shows how to get rowid of clicked row. The Boolean value returned from beforeSelectRow allows you to deny selection of row by click on the icon (if it's required of cause). One need just return false from beforeSelectRow to prevent selection.

Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Thanks.. How can we alert value of current row's GameName alomg with "HELLO"? – LCJ Jul 27 '15 at 13:18
  • 1
    @Lijo: You use `loadonce: true`. So the data returned from the server will be saved locally in `data`. You can use `var rowData = $self.jqGrid("getRowData", rowid);` to get the row data by `rowid`. It's the reference to the original item of data which saves jqGrid internally. So `rowData.GameName` is the non-formatted content of `GameName` returned from the server. Alternatively you can get it from the cell of jqGrid an unformat it. It's more slow, but you can use it too (especially if `loadonce: false`): `var gameName = $self.jqGrid("getCell", rowid, "GameName");` – Oleg Jul 27 '15 at 13:28
  • Thanks, it worked... It would be good if you can edit your answer with the above comment so that the answer will be more complete. – LCJ Jul 27 '15 at 14:50
  • @Lijo: You are welcome! I did the modifications. I have to mention that my previous comment have copy/pased error. It's more effective to use `getLocalRow` in case of `loadonce: true`, but one can use `getRowData` or `getCell` is `loadonce: false`. By the way: Do you tried [the answer](http://stackoverflow.com/a/31647535/315935)? – Oleg Jul 27 '15 at 15:37
0

Well, I'm not too sure about efficiency of the solution, but you can make the data in the rows have an event handler like:

$(document).on("click", "#id", function(){});

Then you can use $(this).val(); to find the value of the element.

Does that answer your question???

SML
  • 214
  • 2
  • 3
  • 12