How to get the Value of an ID from a TR of a Clicked TD Element

9k views Asked by At

I have a dynamically created table as:

<div id="gameListDiv">
<table id="gameListTable">
    <tr id="1">
        <td>A</td>
        <td>B</td>
        <td class="tpButton">C</td>
    </tr>
    <tr id="2">
        <td>D</td>
        <td>E</td>
        <td class="tpButton">F</td>
    </tr>
</table>
</div>

I have a listener:

$('#gameListDiv').on('click','.tpButton', function(toggleThisTP) {
    // If user clicks C, return the row ID of '1'
    // if user clicks F, return the row ID Of '2'
});

As in the code comments just above, how to I get the value if the ID tag of the specific row when the user clicks a cell in the 3rd column of the table?

3

There are 3 answers

4
Douwe de Haan On BEST ANSWER

This should work:

$('#gameListDiv').on('click','.tpButton', function() {
    var id = jQuery(this).closest('tr').attr('id');
    alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="gameListDiv">
<table id="gameListTable">
    <tr id="1">
        <td>A</td>
        <td>B</td>
        <td class="tpButton">C</td>
    </tr>
    <tr id="2">
        <td>D</td>
        <td>E</td>
        <td class="tpButton">F</td>
    </tr>
</table>
</div>

Link to closest() documentation

3
AmmarCSE On

Use jQuery closest() and attr()

$('#gameListDiv').on('click','.tpButton', function(toggleThisTP) {
    var row = $(this).closest('tr');
    var id = row.attr('id');
});
1
areeb On

Use Class

<div id="gameListDiv">
<table id="gameListTable">
    <tr class="gamelist" id="1">
        <td>A</td>
        <td>B</td>
        <td class="tpButton">C</td>
    </tr>
    <tr class="gamelist" id="2">
        <td>D</td>
        <td>E</td>
        <td class="tpButton">F</td>
    </tr>
</table>
</div>

Jquery

$(".gamelist").click(function(){
   var id = $(this).attr('id'); 
   alert(id);
});