How to Get Button Index?

How to Get Button Index?

LucidLucid Posts: 7Questions: 3Answers: 0

I've got several buttons at the top of my DataTable (Print, ExportToFile, SaveToPDF, etc...). And I'm looking to dynamically add/remove some of them. To allow for various button scenarios, I'm hoping someone can shed some light on how I can get the index of a particular button?

XXOXXXX
XXXXXOX
XXXXOXX

How would I determine where "O" is in the order of buttons so that I could remove it and add a different one in its place?

I can get the "text()" of a button (which doesn't really help me since I use images and no Text), but I can't seem to get the Index for the button.

var table = $('#myDataTable').DataTable();
var numOfButtons = table.buttons().count();
for (i = 0; i < numOfButtons; i++) {
   console.log('button text: ' + table.button(i).text());
}

Can someone point me in the right direction?
Thanks!

This question has an accepted answers - jump to answer

Answers

  • rf1234rf1234 Posts: 3,000Questions: 87Answers: 421

    You can assign names to your buttons and then address them by name like this

    .....
    buttons: [
                {   extend: "whatAButton", name: "myButton" }
    ]
    .....
    
    table.buttons('myButton:name').nodes().addClass('hidden');
    

    You can also loop through your buttons and hide a couple of them. Then you see what the numbers are. With the name or className - whatever you prefer - you don't need those numbers any longer.

    for (i=0; i < 2; i++) {
         table.button(i.toString()).nodes().addClass('hidden');
    }
    
  • LucidLucid Posts: 7Questions: 3Answers: 0

    Sorry, I'm still a little confused. How do I get the index of a particular button? Isn't there an "index" or a "buttonIndex" property or something I can snag?

    I went ahead and reworked my code to not rely on having to know the Index of a particular button, but if someone knows how to easily get it, I'd still be interested in having that for future reference...

    Thanks!

  • rf1234rf1234 Posts: 3,000Questions: 87Answers: 421

    just jQuery, but you need to assign a class first.

    .....
    buttons: [
                {   extend: "whatAButton", className: "myButton" }
    ]
    .....
    alert ($('.myButton').index());
    
  • rf1234rf1234 Posts: 3,000Questions: 87Answers: 421
    Answer ✓

    or using the api with name (also works with className of course)

    .....
    var table = $('#myDataTable').DataTable();
    
    buttons: [
                {   extend: "whatAButton", name: "myButton")
    ]
    .....
    alert (table.buttons('myButton:name').nodes().index());
    
  • LucidLucid Posts: 7Questions: 3Answers: 0

    I see what I was doing wrong now. Thanks a bunch for the examples!

This discussion has been closed.