Stephen Fox Stephen Fox - 6 months ago 16
Javascript Question

Get row index of table in jQuery

I want to get the index of a element within the following table when the user clicks on a row.

<table class="table table-hover" id="event_table">
<thead>
<tr>
<th>Event Title</th>
<th>Event Location</th>
<th>Event Time</th>
<th>Event Date</th>
</tr>
</thead>
<tbody>

<tr>
<td>Gathering</td>
<td>City Centre</td>
<td>10:30</td>
<td>10/09/2016</td>
</tr>
<tr>
<td>Meetup</td>
<td>Some place</td>
<td>12:30</td>
<td>15/09/2016</td>
</tr>


</tbody>
</table>


How would I do this with jQuery?
I have tried something similar to this:

$("#event_table tbody tr").on("click", function() {
$(this).index();
});

Answer

Your code works just fine:

$("#event_table").on("click", "tbody tr", function() {
   alert($(this).index()); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="table table-hover" id="event_table">
    <thead>
      <tr>
        <th>Event Title</th>
        <th>Event Location</th>
        <th>Event Time</th>
        <th>Event Date</th>
      </tr>
    </thead>
    <tbody>
        <tr>
          <td>Gathering</td>
          <td>City Centre</td>
          <td>10:30</td>
          <td>10/09/2016</td>
        </tr>
        <tr>
          <td>Meetup</td>
          <td>Some place</td>
          <td>12:30</td>
          <td>15/09/2016</td>
        </tr>
    </tbody>
  </table>