Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Id of current table row with Jquery

Tags:

html

jquery

Hi I have the following code in a form . When the user clicks a button I want to get the current row in order to identify which of the buttons was clicked

<tr  id="TEST1" >     <td align="left" valign="middle">         <div align="right">Contact</div>     </td>     <td colspan="4" align="left" valign="middle">         <input type="text" id="contact1" size="20" />  Number          <input type="text" id="number1" size="20" />      </td>     <td>         <input type="button"  value="Button 1" id="contact1" />     </td> </tr> <tr id="TEST2" >     <td align="left" valign="middle">         <div align="right">Contact</div>     </td>     <td colspan="4" align="left" valign="middle">         <input type="text" id="contact2" size="20" />  Number          <input type="text" id="number2" size="20" />      </td>     <td>         <input type="button"  value="Button 1"  id="contact2" />     </td> </tr> <tr id="TEST3" >     <td align="left" valign="middle">         <div align="right">Contact</div>     </td>     <td colspan="4" align="left" valign="middle">         <input type="text" id="contact3" size="20" />  Number          <input type="text" id="number3" size="20" />      </td>     <td>         <input type="button"  value="Button 1"  id="contact2" />     </td> </tr> 

I thought the following Jquery would return the ID name but it doesn't

$('input[type=button]' ).click(function() {     bid = (this.id) ; // button ID      trid = $('tr').attr('id'); // table row ID  }); 

Can anyone give me some advice please ? thanks

like image 842
Mick Avatar asked Sep 27 '10 20:09

Mick


People also ask

How to get current Table row Id using jQuery?

$(function() { var bid, trid; $('#test tr'). click(function() { trid = $(this). attr('id'); // table row ID alert(trid); });


1 Answers

You can use .closest() to get up to the current <tr> parent, like this:

$('input[type=button]' ).click(function() {    var bid = this.id; // button ID     var trid = $(this).closest('tr').attr('id'); // table row ID   }); 
like image 173
Nick Craver Avatar answered Sep 21 '22 00:09

Nick Craver