rakesh
rakesh

Reputation: 985

how to find clicked tr from tbody jquery

This is my html table

<table>
    <thead>
        <tr>
            <td class="td20"><h3>Patient Name</h3></td>
            <td class="td20"><h3>Summary</h3></td>
            <td class="td20"> <h3>Created</h3></td>
            <td class="td20"><h3>Last visit</h3></td>
            <td class="td20"> <h3>Refer to a Doctor</h3></td>
        </tr>
    </thead>
    <tbody id="patient_table">
        <tr id="1">
            <td class="td20">Patient Name</td>
            <td class="td20">Summary</td>
            <td class="td20">Created</td>
            <td class="td20">Last visit</td>
            <td class="td20">Refer to a Doctor</td>
        </tr>
        <tr id="2">
            <td class="td20">Patient Name</td>
            <td class="td20">Summary</td>
            <td class="td20">Created</td>
            <td class="td20">Last visit</td>
            <td class="td20">Refer to a Doctor</td>
        </tr>
    </tbody>
</table>

This is my script:

$("#patient_table").click(function(e) {
    var id = $(this).children('tr').attr('id');
    alert(id);
});

The <tr> is generated dynamically inside the <tbody>. I need to find the id of <tr> on click of <tr> itself. With the script I'm always getting the first <tr> id only irrespective of the second <tr> click.

Upvotes: 0

Views: 3130

Answers (1)

j08691
j08691

Reputation: 207861

Use this instead:

$("#patient_table").on('click','td',function (e) {
    var id = $(this).closest('tr').attr('id');
    alert(id);
});

jsFiddle example

Since you mentioned the rows being generated dynamically you want to use .on() to delegate the event handling to the table cells.

Upvotes: 4

Related Questions