user3217883
user3217883

Reputation: 1465

why won't jquery datatable respond to click?

I have a jquery datatable that populates from ajax but when I click on a row, the table click event handler does not fire. Here is my datatable:

function initDataTables(watchlist) {
    $('#watchlistTable').DataTable({
        ajax: {
            url: "/MoneyMachine/getWatchlist.php",
            type: "post",
            data: {watchlist:watchlist}
        },
        columns: [
            { data: 'Symbol' },
            { data: 'CompanyName' },
            { data: 'ClosePrice', class: 'text-right' },
            { data: 'PricePctChangeToday', class: 'text-right'},
            { data: 'CAGR', class: 'text-right'},
            { data: 'BenchmarkCAGR', class: 'text-right'},
            { data: 'DivYield', class: 'text-right'},
            { data: 'ExDivDate'},
            { data: 'AppreciationPotential', class: 'text-right'}
        ],    
        responsive: true,   //supposedly make table clickable but does nothing
        destroy: true       //A data table can only be initialized once.  It must be destroyed so it can be initialized again.      
    });
}

I've tried a couple different click events like this:

$('.dataTable').on( 'click', '.dataTable', function () {
    console.log("watchlistTable was clicked");
});

And like this:

$('#watchlistTable tbody').on( 'click', 'tr', function () {
    console.log("watchlistTable was clicked");
});

And like this:

$('.display').on( 'click', '.display', function () {
    console.log("watchlistTable was clicked");
});

But neither one fires. Here is the html for it:

        <table id="watchlistTable" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Sym</th>
                <th>Company Name</th>
                <th>Price</th>
                <th>Change%</th>
                <th>CAGR</th>
                <th>Benchmark<br>CAGR</th>
                <th>Div<br>Yield%</th>
                <th>Ex-Div<br>Date</th>
                <th>App<br>Pot%</th>
            </tr>
        </thead>
        </table>

Upvotes: 2

Views: 61

Answers (1)

charlietfl
charlietfl

Reputation: 171669

My guess is you aren't including a <tbody> in the original html

Try adding it to the target selector and delegating to the table itself instead

$('#watchlistTable').on( 'click', 'tbody tr', function () {...

Note that $('.dataTable').on( 'click', '.dataTable', ... is trying to delegate to an existing class dataTable and would only be triggered on other elements with that class that are inside it. Since nothing in the html shown has that class it's not clear what that element would even be and I doubt you have nested elements with same class

Upvotes: 1

Related Questions