webKite
webKite

Reputation: 275

HTML table, clicked row's number

Is there any way to find out row number where I recently clicked, in HTML table? I need this behavior to find out whether use clicked on top and bottom of the currently selected row.

I suppose the algorithm will be:

  1. select one row
  2. select another row in same table
  3. find out if the row selected at (2) has higher or lower index than row selected at (1)

Upvotes: 1

Views: 3016

Answers (3)

Pete Wilson
Pete Wilson

Reputation: 8694

Adding this answer because versions of IE don't understand some index operations; and because a reader might find it convenient to use pure JS rather than jQuery in this case:

Each <tr> is a children[children_index] of <tbody>. You can look in the DOM to find it and its zero-based index.

Upvotes: 1

Bas Slagter
Bas Slagter

Reputation: 9929

Maybe you can take a look at this question, which is somewhat similar: table row and columns number in jQuery. Of course, I can give you a hint:

var rowIndex = $("#myrow").index();

Upvotes: 2

James Allardice
James Allardice

Reputation: 165971

As you've tagged the question with jQuery, I'll give you a jQuery answer. You can get the index of the clicked row using jQuery's index method:

$("tr").click(function() {
   console.log($(this).index()); 
});

Inside the click event handler, you would be able to use the index method again to get the index of the currently selected row and compare them or do whatever you're trying to do.

Upvotes: 3

Related Questions