Thomas
Thomas

Reputation: 34208

Want to get table row id when click on any cell of table

suppose i have html table and each TR has id. every TR has some TD and some TD has input controls and some may have text inside in.

when click on TD or control should return immediate TR id.

i tried this below script which works fine but when i click on text like hello1 then TR id does not return.

see the script and tell me what is missing.

<div id="grd1">
    <table>
        <tr id="t1"><td tabindex="0"><span>Hello1</span></td><td tabindex="1"><input /></td><td tabindex="2"><input /></td></tr>
        <tr id="t2"><td tabindex="3"><span>Hello2</span></td><td tabindex="4"><input /></td><td tabindex="5"><input /></td></tr>
    </table>
</div>

$('#grd1 table tr').on('focus', ':input', function(event) {
    alert($(this).closest('tr').attr('id'));
});

Upvotes: 0

Views: 3256

Answers (3)

Steve Harris
Steve Harris

Reputation: 5109

Give the table an id eg 'table':

$('#table').children('tbody').children('tr').each(function () {
   var $row = $(this);
   $row.find('input').on('focus', function () {
       alert($row.get(0).id);
   });
});

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167240

Since you are using an advanced selector, I suggest you do some changes:

  1. Change :input to input.
  2. The id call, change it to below.
  3. I believe the <tr> is also dynamic, so add it with the delegation.

Corrected Code:

<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<div id="grd1">
  <table>
    <tr id="t1"><td tabindex="0"><span>Hello1</span></td><td tabindex="1"><input /></td><td tabindex="2"><input /></td></tr>
    <tr id="t2"><td tabindex="3"><span>Hello2</span></td><td tabindex="4"><input /></td><td tabindex="5"><input /></td></tr>
  </table>
</div>
<script>
  $('#grd1 table tr').on('click focus', 'td, input, th', function(event) {
    alert($(this).closest('tr').attr('id'));
  });
</script>

The Alert Duh!!!

Upvotes: 0

Shyju
Shyju

Reputation: 218892

Use the table cell(td) as the selector and listen for click event.

$(document).on('click', '#grd1 td', function(event) {
    alert($(this).closest('tr').attr('id'));
});

Here is a working sample

Upvotes: 1

Related Questions