Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding click events to Datatables

Here is my Jquery data tables to get the values from ajax and placing it.

$(document).ready(function() {
    $('#example').DataTable({
        "ajax": "data/arrays.txt"
    });
});

Here is the constructed table.

I want to write click function to it. How can i do it ?

<table id="example" class="table dataTable no-footer" role="grid" aria-describedby="example_info" style="width: 299px;">
    <tbody>
        <tr role="row" class="odd">
            <td class="sorting_1">TMB030</td>
            <td>Sample Collected</td>
        </tr>
        <tr role="row" class="even">
            <td class="sorting_1">TMB033</td>
            <td>Sample Collected</td>
        </tr>
    </tbody>
</table>

I want to write click event to the role="row" and get the value TMB030 on it.

How can i do that ?

I tried like this

$(document).ready(function() {
    $('#example').DataTable({
        "ajax": "myOrders/" + Cookies.get('userSession')
    });
    $("div[role='row']").click(function() {
        alert('clicked')
    });
});

But it is not triggered how can i do that ? Help pls

like image 761
SA__ Avatar asked May 19 '16 07:05

SA__


1 Answers

It should be like this:

$( document ).on("click", "tr[role='row']", function(){
    alert($(this).children('td:first-child').text())
});

Brief Explanation:

  1. On initial page load(that is when document.ready callback function is executed), the Datatable elements (rows and columns etc) are not yet present in the DOM Tree. They are created at runtime in response to data changes. Therefor the callback function provided in document.click method will not get bind to any element (i.e. div[role='row']).
  2. To overcome it, .on method is available. It binds the callback function to click event of elements already in the DOM and also to elements that are created dynamically.
like image 160
Naqash Malik Avatar answered Oct 11 '22 12:10

Naqash Malik