JQuery: get table id by td button

I have tr in the table header, which contains several input fields.

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

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> 

Thanks for any help with this, Tim.

+6
source share
4 answers

In the click handler you can use .closest ()

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

+28
source
 $("#tableID").on("click","input[type='text']",function(){ $(this).closest('table').attr('id'); }); 

link closest ()

+2
source

you can use

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

it works.

+1
source

You should delegate the event to avoid using multiple handlers, and then use delegateTarget to configure the current TABLE table:

 $('table').on('click', 'input', function (e) { alert(e.delegateTarget.id); }); 
0
source

Source: https://habr.com/ru/post/958726/


All Articles