Search code examples
javascriptjquerydatatablesdatatables-1.10tabletools

Enabling custom button (disabled by default) when row is selected


I have a DataTable displaying data for Branches with two custom buttons defined: Add and Update. They are initialized at the top of the Javascript section

var buttons;
var tblBranch;

$.fn.dataTable.ext.buttons.add = {
            className: 'button-add',
            text: "Add Branch",
            action: function (dt) {
                onBtnAddClicked()
            }
        };

$.fn.dataTable.ext.buttons.update = {
            className: 'button-update',
            text: "Update",
            action: function (dt) {
                onBtnUpdateClicked()
            }
        };

I'd like to disable the Edit button on page load and only enable it to be clickable when a row has been selected. Problem is, I'm using custom buttons and I can't find anything on datatables.net about how to enable/disable them depending on conditions. So far what I've tried is this:

tblBranch = $("#tblBranches").DataTable({
        dom: 'Blfrtip',
        buttons: {
            buttons :[
                'add', 'update'
            ]
        }
        select: true;
})

$("#tblBranches tbody").on('click', 'tr', function () {
        if (tblBranch.row(this).hasClass('selected')) {
             $('button-update').removeClass("DTTT_disabled");
        }
        else {
             table.$('tr.selected').removeClass('selected');
             $('button-update').addClass("DTTT_disabled");
        }
});

But I don't know what the code to disable the Edit button when the page loads should be like, and I've looked here, here, here and here.

Thanks for any guidance.


Solution

  • The last link you are referring to hold the solution you are looking for. But the documentation is a little bit vague, guess it need a solid example. It is not clear how you create the buttons (you show both methods) but below is an inline example, it would work with constructor as well. Simply give the button a class, like .edit and set it to disabled from start :

    var table = $('#example').DataTable( {
      dom: 'Bfrtip',
      select: true,
      buttons: [
        {
          text: 'Edit',
          className: 'edit',
          enabled: false,
          action: function (e, dt, node, config) {
            //do something
          }
        },
        {
          text: 'Add',
          action: function (e, dt, node, config) {
            //do something
          }
        }
      ]
    })
    

    Then use the Select plugins select and deselect events to update the enabled status of the .edit button :

    $('#example').on('select.dt deselect.dt', function() {
      table.buttons( ['.edit'] ).enable(
        table.rows( { selected: true } ).indexes().length === 0 ? false : true
      )
    })
    

    demo -> https://jsfiddle.net/pmee6w2L/