Search code examples
javascriptjqueryjqgridfree-jqgrid

How to select the row Id from custom formatter?


I am trying to get the selected row ID when I click on the icon and/or link from a custom formatter but I am not able to get it, As soon as I click on the icon nothing happen (you can see it on the Fiddle). This is how the code I am working on looks like:

  $.fn.fmatter.customActionsFormatter = function(cellValue, options, rowData) {
    return '<a href="#" class="delete_row" title="Delete selected row"><span class="fa fa-fw fa-trash-o delete_row" data-id="' + rowData.Id + '"></span></a>';
  };


  $(".delete_row").click(function() {
    var rowid = $("#list").jqGrid('getGridParam', 'selrow');

    alert(rowid);
  });

Why is this not working?

I have created a Fiddle showing the issue. Just select one and try to click the icon you'll see how nothing happen


Solution

  • Use event delegation,

    Taken from Jquery Learning Center https://learn.jquery.com/events/event-delegation/

    Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

    $(document).on('click', '#list .delete_row', function(event) {
        event.preventDefault();
        var rowid = $("#list").jqGrid('getGridParam', 'selrow');
        alert(rowid);
    })
    

    As .delete_row icon is created in the custom formatter callback (and therefore appended with Javascript) the .delete_row elements you are looking for don't exists yet at the time you bind your events(They will exists when the jqgrid will finish rendering and the customFormatter triggered)