Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find rowindex when clicked a button in table

I want to find row which clicked button in.

<table>
  <tr>
    <td>foo 1</td>
    <td><input  type="button" value="Remove" id="remove1"/> </td>
  </tr>
  <tr>
    <td>foo 2 </td>
    <td><input  type="button" value="Remove" id="remove2"/> </td>
  </tr>
</table>

My table struct is like above. Normally I can us buttonid to get row index. But If I remove a row (tr) another row index changes. For example:

If I remove first row with jQuery, second row index changes as 0 then I cannot use button's id. (remove - 2 )

Well I think that I must use parent function but it doesn't work.

var elem = $('#remove2');
alert(elem.parent()[0].sectionRowIndex);

I tried this one but doesn't work. I need row index that clicked button in the row.

I hope that I explained my issue.

like image 677
ertan2002 Avatar asked Jan 01 '13 17:01

ertan2002


People also ask

How do I get current rowIndex of a table using Javascript?

var index = $('table tr'). index(tr);

How do I get the row number in HTML?

The selectors used for finding the number of rows and columns in an HTML table are: To count the number of rows, the “#Table_Id tr” selector is used. It selects all the <tr> elements in the table.

How do I add a row to a table in button click?

To add a row, define a variable that keeps the count of the total number of that now exists in the table. Then we will use the jQuery “click” event to detect a click on the add row button and then use the . append() method of jQuery to add a row in the table.


2 Answers

Try this:

$("table tr input").on('click', function(e){
   alert($(this).closest('td').parent()[0].sectionRowIndex);
});​

FIDDLE

like image 90
palaѕн Avatar answered Oct 04 '22 06:10

palaѕн


Try using this: http://jsfiddle.net/jd9N4/1/

var elem = $('input[type="button"]');
$(elem).click(function() {
   alert($(this).closest('tr').index());
   $(this).closest('tr').remove();
});
like image 21
Jai Avatar answered Oct 04 '22 06:10

Jai