Cell Data and Index on Row Click

Cell Data and Index on Row Click

polarimanpolariman Posts: 6Questions: 2Answers: 0

Assuming I have a table with 5 columns, how can I get the column index as well as the data in cell 5 when a row is clicked. In essence, how do I access the information in the row data object?

This question has an accepted answers - jump to answer

Answers

  • ignignoktignignokt Posts: 146Questions: 4Answers: 39
    edited November 2014 Answer ✓

    This is how you'd get the row object when a row or cell is clicked. You can use the tr on click if you don't care about the cell they clicked in the row. If you also need to know that then you could use the second example, td on click.

    var table = $('#example').DataTable({
        columns:[
            {sTitle:"Day",data:"day"},
            {sTitle:"Week",data:"week"},
            {sTitle:"Month",data:"month"},
            {sTitle:"Year",data:"year"}
        ],
        processing: true,
        serverSide: true,
        ajax: {
            url:"/myajaxurl",
            type:"POST"
        }
    });
    
    //tr on click
    $(document).on('click','#example tr',function(e){
        var row_object  = table.row(this).data();
        var day         = table.row(this).data()['Day'];
        var week        = table.row(this).data()['Week'];
        var month       = table.row(this).data()['Month'];
        var year        = table.row(this).data()['Year'];
    });
    
    //td on click
    $(document).on('click','#example td',function(e){
        var cell_clicked    = table.cell(this).data();
        var row_clicked     = $(this).closest('tr');
        var row_object      = table.row(row_clicked).data();
        var day             = table.row(row_clicked).data()['Day'];
        var week            = table.row(row_clicked).data()['Week'];
        var month           = table.row(row_clicked).data()['Month'];
        var year            = table.row(row_clicked).data()['Year'];
    });
    
This discussion has been closed.