How to create jqGrid Context Menu?
Asked Answered
D

3

11

I am trying to create a context menu on jqGrid (for each row) but can't find how to do so.I am currently using jQuery Context Menu (is there a better way? )but it is for the entire Grid not for a particular row i.e. cannot perform row level operations for it. Please help me in this, thanks.

$(document).ready(function(){ 
  $("#list1").jqGrid({
    sortable: true,
    datatype: "local", 
    height: 250, 
    colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'], 
    colModel:[ 
        {name:'id',index:'id', width:60, sorttype:"int"}, 
        {name:'invdate',index:'invdate', width:90, sorttype:"date"}, 
        {name:'name',index:'name', width:100}, 
        {name:'amount',index:'amount', width:80, align:"right",sorttype:"float"}, 
        {name:'tax',index:'tax', width:80, align:"right",sorttype:"float"}, 
        {name:'total',index:'total', width:80,align:"right",sorttype:"float"}, 
        {name:'note',index:'note', width:50, sortable:false} 
        ], 
    multiselect: true,
    rowNum:10, 
    rowList:[10,20,30], 
    pager: '#pager1', 
    sortname: 'id', 
    recordpos: 'left', 
    viewrecords: true, 
    sortorder: "desc",
    caption: "Manipulating Array Data"
  });
  $("#list1").jqGrid('navGrid','#pager1',{add:false,del:false,edit:false,position:'right'});

  $("#list1").contextMenu({
        menu: "myMenu"
    },
        function(action, el, pos) {
        alert(
            "Action: " + action + "\n\n" +
            "Element ID: " + $(el).attr("id") + "\n\n" +
            "X: " + pos.x + "  Y: " + pos.y + " (relative to element)\n\n" +
            "X: " + pos.docX + "  Y: " + pos.docY+ " (relative to document)"
            );
    });
Dulosis answered 7/7, 2011 at 8:6 Comment(0)
T
17

There are many context menu plugins. One from there you will find in the plugins subdirectory of the jqGrid source.

To use it you can for example define your context menu with for example the following HTML markup:

<div class="contextMenu" id="myMenu1" style="display:none">
    <ul style="width: 200px">
        <li id="add">
            <span class="ui-icon ui-icon-plus" style="float:left"></span>
            <span style="font-size:11px; font-family:Verdana">Add Row</span>
        </li>
        <li id="edit">
            <span class="ui-icon ui-icon-pencil" style="float:left"></span>
            <span style="font-size:11px; font-family:Verdana">Edit Row</span>
        </li>
        <li id="del">
            <span class="ui-icon ui-icon-trash" style="float:left"></span>
            <span style="font-size:11px; font-family:Verdana">Delete Row</span>
        </li>
    </ul>
</div>

You can bind the context menu to the grid rows inside of loadComplete (after the rows are placed in the <table>):

loadComplete: function() {
    $("tr.jqgrow", this).contextMenu('myMenu1', {
        bindings: {
            'edit': function(trigger) {
                // trigger is the DOM element ("tr.jqgrow") which are triggered
                grid.editGridRow(trigger.id, editSettings);
            },
            'add': function(/*trigger*/) {
                grid.editGridRow("new", addSettings);
            },
            'del': function(trigger) {
                if ($('#del').hasClass('ui-state-disabled') === false) {
                    // disabled item can do be choosed
                    grid.delGridRow(trigger.id, delSettings);
                }
            }
        },
        onContextMenu: function(event/*, menu*/) {
            var rowId = $(event.target).closest("tr.jqgrow").attr("id");
            //grid.setSelection(rowId);
            // disable menu for rows with even rowids
            $('#del').attr("disabled",Number(rowId)%2 === 0);
            if (Number(rowId)%2 === 0) {
                $('#del').attr("disabled","disabled").addClass('ui-state-disabled');
            } else {
                $('#del').removeAttr("disabled").removeClass('ui-state-disabled');
            }
            return true;
        }
    });
}

In the example I disabled "Del" menu item for all rows having even rowid. The disabled menu items forward the item selection, so one needs to control whether the item disabled one more time inside of bindings.

I used above $("tr.jqgrow", this).contextMenu('myMenu1', {...}); to bind the same menu to all grid rows. You can of course bind different rows to the different menus: $("tr.jqgrow:even", this).contextMenu('myMenu1', {...}); $("tr.jqgrow:odd", this).contextMenu('myMenu2', {...});

I didn't read the code of contextMenu careful and probably the above example is not the best one, but it works very good. You can see the corresponding demo here. The demo has many other features, but you should take the look only in the loadComplete event handler.

Tumulus answered 7/7, 2011 at 9:58 Comment(7)
Awesome! Definitely going to be implementing this in my instance of jQGridCraniate
@FastTrack: I suggested later some add-ons to the context menu. See for example the demo from the answer and some other. See the post also.Tumulus
there should be a way to implement this solution in JqGrid for PHP, too. here is the questionRas
@Tumulus - thanks! this method works well for me as well, but I have one issue - the inline style rules for the ul element ("width:200px") seem to be overwritten somehow. I see this happening in your example as well. Any way to get around this? (My context menu options are longer)Shape
@froadie: You are welcome! The answer is really old. For example making separate binding of conetxMenu to every tr.jqgrow is not good. It's better to bind the event to <table> element once. Moreover one have now new versions of jQuery UI, moreover there are two forks of jqGrid: free jqGrid which I develop and Guriddo jqGrid JS which Tony develop. There are two close plugins in github.com/free-jqgrid/jqGrid/tree/master/plugins. It would be better if you post separate question with all detailsTumulus
@Tumulus - thanks for the quick response, will try to formulate a new questionShape
@Tumulus - #34608298Shape
T
5

you can have a look at the onRightClickRow event

JqGridWiki

jQuery("#gridid").jqGrid({
...
   onRightClickRow: function(rowid, iRow, iCol, e){ 
      //Show context menu ...

   },
...
})

From Wiki ... onRightClickRow

Event Name

onRightClickRow

Parameters

rowid, iRow, iCol, e

Information

Raised immediately after row was right clicked. rowid is the id of the row, iRow is the index of the row (do not mix this with the rowid), iCol is the index of the cell. e is the event object. Note - this event does not work in Opera browsers, since Opera does not support oncontextmenu event

Thedathedric answered 7/7, 2011 at 8:11 Comment(5)
how would I inflate context menu here?Dulosis
If you can find a contextMenu with a show() method you could use it in the rightclickevent. Or another solution is to create a own div and call $('div').show() when user right click the row...Thedathedric
So I guess there is no context menu in jqGrid. There is one example of ASP.NET MVC code with ContextMenu but I can't find its equivalent in simple jQuery. trirand.net/examples/functionality/contextmenu/default.aspxDulosis
you could use the same approach.. 1) Assign a class to each row 2) attach the context menu to all DOM element with that class 3) On the ContextMenu function(action, el, pos) get the row data like you do now ($(el).attr("id"))Thedathedric
I might have to cater half a million rows (at occasions). Won't this approach be a bit expensive?Dulosis
I
1

You can try this :

jQuery("#yourid").jqGrid({

...

{name:'req_name',index:'req_name', width:'9%', sortable:true},

.....

 loadComplete:function(request){

...

               $("[aria-describedby='yourid_req_name']", this).contextMenu('myMenu1',{ 
                    onContextMenu: function(e) {
                        var rowId = $(e.target).closest("tr.jqgrow").attr("id");
                            $("#send").html('<a onclick="send_email('+rowId+')">Send Email</a>');
                            return true;    
                    }
                });
},

........... and the html code :

<div class="contextMenu" id="myMenu1" style="display:none">
        <ul style="width: 400px">
            <li id="send">
                <span>Add Row</span>
            </li>
        </ul>
    </div>
Illa answered 26/5, 2014 at 6:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.