J-J
J-J

Reputation: 1113

How to get index of selected row in html table using jquery?

I am trying to get the row index of selected row in html table using below code but it doesn't work.

    $(function() {

        $("#myTable tr").click(function() {
            alert(this.rowIndex);
        });
    });

What must be the problem with the above code?

Upvotes: 1

Views: 6373

Answers (3)

Sandipan Guha
Sandipan Guha

Reputation: 126

Same problem I tried to solve few days back. You can use this code as a template for similar problems. I will comment on the way.

    window.onload = function() {

    /* variable stores html data as array for desired tag, this case it's 'tr' -*/

          var test = this.test = $('tr'); 

/* loop traverses the row elements in the array, which element is clicked */

    for (var i = 0; i < test.length; i++){
          index = Array.prototype.indexOf.call(test,test[i]);

/* it's best to store the index inside the original row element which eases the access */

          test[i].setAttribute('index',index); 

    /* on clicking the element it calls for a function which alerts the index */

          test[i].onclick = alertTheClick ;

    /* this is in case of debug */
          console.log(index);

       }
    };

    /* function definition */
    function alertTheClick(index){       /* index value from loop */
       alert(this.getAttribute('index'));  /* index attribute from 'tr' element */
    }

Upvotes: 0

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

Your code look fine, unless you did't add jQuery references like other said AND/OR maybe your table was created dynamically, try using .on for event delegation like so :

$(function() {
    // use event delegation
    $(document).on('click','#myTable tr', function() {
        alert(this.rowIndex);
        // or
        alert($(this).index()); // jQuery way
    });
});

Upvotes: 3

guradio
guradio

Reputation: 15555

$('#table tr').each(function(indx, val) {
  $(this).click(function() {
    var index = $(this).index();
    var value = $(this).text();
    alert('This row index is ' + index + ' This row value is ' + value)
    console.log(indx)
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='table'>
  <tr>
    <td>qwe</td>
  </tr>
  <tr>
    <td>123</td>
  </tr>
  <tr>
    <td>123qwe</td>
  </tr>
</table>

You can use .index() to get the index of tr.

Description: Search for a given element from among the matched elements.

Documentaion

Also you can use the parameter using .each function

Description: Iterate over a jQuery object, executing a function for each matched element.

Documentaion

Upvotes: 0

Related Questions