Search code examples
jqueryajaxdatatablescontextmenuright-click

How to show edit and delete buttons on datatables when right clicking a row?


I am using datatables. Is it possible to show working edit and delete buttons on right click like the example here? The only working example I found is this. But it is not what I am trying to achieve.

Example for click events: https://datatables.net/examples/advanced_init/events_live.html


Solution

  • You could init the contextmenu in the drawCallback handler, and retrieve the id from the clicked row in $.contextMenu's own callback :

    drawCallback : function() {
      $.contextMenu({
            selector: 'tbody tr td', 
            callback: function(key, options) {
                var id = options.$trigger[0].parentElement.id;
                var m = "clicked: " + key + ' ' + id;
                window.console && console.log(m) || alert(m); 
                /*
                 switch (key) {
                   case 'delete' :
                     yourDeleteMethod(id); break;
                   case 'edit' :
                     yourEditMethod(id); break;
                   ...
                  }
                */ 
            },
            items: {
                "edit": {name: "Edit", icon: "edit"},
                "cut": {name: "Cut", icon: "cut"},
               copy: {name: "Copy", icon: "copy"},
                "paste": {name: "Paste", icon: "paste"},
                "delete": {name: "Delete", icon: "delete"},
                "sep1": "---------",
                "quit": {name: "Quit", icon: function(){
                    return 'context-menu-icon context-menu-icon-quit';
                }}
            }
        });
    },
    

    updated fiddle -> http://jsfiddle.net/0f9Ljfjr/900/

    Since the selector is set to tbody tr td the id will always could be found by options.$trigger[0].parentElement.id. Now you just need to respond to what ever actions you need, and call your own methods with the retrieved id.