1

I've created a table with three rows that can be expanded with the use of an add button. I want to know the index of every row I click. I have a piece of code that works just fine on the three automatically generated rows, but not on the rows I add using the add button.

Here's a fiddle basically shows my issue: http://jsfiddle.net/4wa5kfpz/, my actual code has a lot more stuff in it so this is a basic/stripped version.

As you can see, the rows added between the first two and last do not respond when clicked. I've tried something like (see below, based on this question) to add the click event to the table rows, but that didn't work.

$("table tr").on('click', '#myTable tr', function(e){
    alert('Clicked row '+ ($(this).index()+1) );
});

Any ideas?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tomjesch
  • 492
  • 4
  • 27

2 Answers2

2

Use .on event:

$("#myTable").on('click', 'tr', function(){
      alert('Clicked row '+ ($(this).index()+1) );
});

http://jsfiddle.net/4wa5kfpz/1/

pavel
  • 26,538
  • 10
  • 45
  • 61
  • Thanks, this worked out excellent! Does this also apply when using an 'each' loop for looping though the dynamically created rows? – Tomjesch May 15 '15 at 12:06
0

You can do like this:

<html>
<head>
<title>Row indexes</title>
<script type="text/javascript">
onload = function() {
    if (!document.getElementsByTagName || !document.createTextNode) return;
    var rows = document.getElementById('my_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (i = 0; i < rows.length; i++) {
        rows[i].onclick = function() {
            alert(this.rowIndex + 1);
        }
    }
}
</script>
</head>
<body>
<table id="my_table">
<tbody>
    <tr><td>first row</td></tr>
    <tr><td>second row</td></tr>
</tbody>
</table>
</body>
</html>

alternatively you could do like this:

$('#thetable').find('tr').click( function(){
  alert('You clicked row '+ ($(this).index()+1) );
});

Hope this will help you!!!

Aman Khanna
  • 137
  • 1
  • 10