-2

I have a simple table :

<table>
    <tr>
        <td>ID</td>
        <td><a href="http:link" class="btn btn-default" data-action="view" 
 data-id="44">View</a>
        </td>
    </tr>
</table>

I would like after click get a data-action and data-id i tried

$('#visit-list-table tr').on('click', function() {
    var test = $(this).closest("tr");
    console.log(test[0].data('id'));

    var test = $(this).closest("tr").find('a').attr('id');
    console.log(test);
});

But without result. How can I get this data?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Wraith
  • 504
  • 6
  • 28

2 Answers2

2

Check below snippet. You should use data attribute like

$(this).closest("tr").find('a').data('id')

Or

$(this).closest("tr").find('a').attr('data-id')

Both will give same result. And i added id 'visit-list-table' to the table.

$('#visit-list-table tr').on('click', function() {
 
  var test = $(this).closest("tr").find('a').data('id');
  console.log(test);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="visit-list-table">
    <tr>
        <td>ID</td>
        <td><a href="http:link" class="btn btn-default" data-action="view" 
 data-id="44">View</a>
        </td>
    </tr>
</table>
Nirali
  • 1,776
  • 2
  • 12
  • 23
0

add id #visit-list-table to element. and you can do $(this).find('a').attr('data-id'); Here attr('data-id') instead of attr('id') because there is no attribute in a tag with id

$('#visit-list-table tr').on('click', function() {
    var test = $(this).find('a').attr('data-id');
    console.log(test);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="visit-list-table">
    <tr>
        <td>ID</td>
        <td><a class="btn btn-default" data-action="view" 
 data-id="44">View</a>
        </td>
    </tr>
</table>
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71