10

I have a tr in a table header that contains several input fields.

Is there a way that by click on one of these input fields I can get the id of the parent table ?

My tr looks like this:

<table id="tableID">
    <thead>
        <tr>
            <th><input type="text" name="input1" id="input1" /></th>
            <th><input type="text" name="input2" id="input2" /></th>
            <th><input type="text" name="input3" id="input3" /></th>
        </tr>
    </thead>
    <tbody>
        // ...
    </tbody>
</table>
halfer
  • 19,824
  • 17
  • 99
  • 186
user2571510
  • 11,167
  • 39
  • 92
  • 138

4 Answers4

39

In the click handler you can use .closest()

$(this).closest('table').attr('id')

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2
$("#tableID").on("click","input[type='text']",function(){

$(this).closest('table').attr('id');

});

reference closest()

Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55
1

You should delegate event to avoid multiple handlers, and then use delegateTarget to target current TABLE:

$('table').on('click', 'input', function (e) {
    alert(e.delegateTarget.id);
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

You can use

$('#tdId').click(function(){
    $(this).parents('table').attr('id');
});

it works.

Meer
  • 1,006
  • 10
  • 15