peace_love
peace_love

Reputation: 6471

How can I get specific data by clicking on a table row?

By clicking on a row, I want to get the data of it. To be precise I actually always need the output of the "id".

   <table id="projects">
       <thead>
            <tr>
              <th>Title</th>
              <th>Company</th>
              <th>Text</th>
              <th>ID</th>
            </tr>
       </thead>
 </table>

var projects = $('#projects').DataTable({
        "ajax": {
            "url": "data/projects.json",
            "dataSrc": "",
        },
       "columns": [

            {
                "data": "title"
            },
            {
                "data": "company"
            },
            {
                "data": "text"
            },
            {
                "data": "id"
            }
        ],
   });


    $('#projects tbody').on('click', 'tr', function () {
        var data = projects.row( this ).data();
        alert( 'You clicked on '+data[0]+'\'s row' );
    } );

projects.json:

[{
    "id": "24",
    "title": "Animals",
    "text": "something",
    "company": "inc"
},

This is giving me the output:

You clicked on undefined's row

What I would need is something like:

$('#projects tbody').on('click', 'tr', function () {
    var data = projects.row( this ).data();
    alert( 'You clicked on '+ row["id"]+'\'s row' );
} );

but this is not giving me an alert.

Upvotes: 0

Views: 40

Answers (1)

user7191279
user7191279

Reputation:

You can access data from a row : $(this).find('td:eq(3)');

Proof : https://jsfiddle.net/tw0a024t/

row[] isn't working because jquery is looking for a html display and not an object.

Upvotes: 1

Related Questions