Can I click a button in a button collection in code?

Can I click a button in a button collection in code?

rdmrdm Posts: 194Questions: 55Answers: 4

TLDR: I'm pretty sure I'm missing something pretty obvious here. How can I click a button in a button collection in code?

To provide context, I have a button collection set that I can manually click on the page, but if it possible to click an extended button in code -- say, after a custom function completes.

Here is an excerpt of the buttons in the configuration block.

buttons: [
    {
        extend: 'collection',
        text: 'Column Visibility',
        buttons: [
            /* more buttons before this... */
            { extend: "colvis", text: 'Toggle Individual' },
            {
                extend: 'colvisGroup',
                text: 'All',
                show: allShow,
                hide: []
            },
            {
                extend: 'colvisGroup',
                text: 'Student',
                show: studentColsShow,
                hide: studentColsHide
            }
            /* more buttons after this... */
        ]

Looking at button().action(), I can see how to identify which button was clicked.

$('#example').DataTable().on('buttons-action',
                function(e, buttonApi) {
                    console.log('Button ' + buttonApi.text() + ' was activated');
                });

My question is how I can do the inverse: click a specific button in code, along the lines of

   $(selector).click();

The problem is that I have been unable to find the correct selector.

In attempt to reverse-engineer it, I used the Chrome Developer Tools to identify the class name of the extended buttons and run it in parallel with the working function. On finding the correct selector, I could then "click" it in code. My attempt to reverse engineer it is an epic failure so far. How can I figure out the correct selector?

$('#example').DataTable().on('buttons-action',
    function(e, buttonApi) {
        console.log('Button ' + buttonApi.text() + ' was activated');
    });

// class name as shown in Chrome Developer Tools
// does not trigger on clicking any extended button
$('.dt-button.buttons-colvisGroup').on('click', function () {
    console.log("this: " + $(this) + " clicked");
});

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,934Questions: 1Answers: 10,155 Site admin
    Answer ✓

    Use the button().trigger() method with a suitable button-selector. For example if your collection is in position index 1 (i.e. the second button shown) and you want to trigger a click on the third button in the collection you would use table.button( '1-2' ).trigger().

    Allan

This discussion has been closed.