views:

33

answers:

1

Hi

I have a table which has 5 rows. When a user clicks on a TR I want to know which row was clicked on (I mean the row number, i.e. 2, 3, or 5).

Does anyone know how to do this?

A: 

You can do something like this (assuming your table has id="mytable"

// Should use DOM readiness instead of window load,
// but for sake of simplicity i'll use onload here
window.onload = function() {
    var rows = document.getElementById('mytable').getElementsByTagName('tr');
    for (var i = 0; i < rows.length; i++) {
        rows[i].onclick = function() {
            var index = -1;
            for (var j = 0; j < rows.length; j++) {
                if (this == rows[j]) {
                   index = j;
                   break;
                }
            }

            // do something with index (0 = first row .. 4 = 5th row)
        };
    }
};

Alternatively, if you use jQuery, you can just do this:

$(document).ready(function() {
    var $rows = $('#mytable tr');
    $rows.click(function() {
        var index = $rows.index(this);
        // do something with index
    });
});
reko_t