get row number in table

R

Roderik

Hi,

I have a table like this:

<table id="myTable">
<tr><td>text</td><td>text</td></tr>
<tr><td>text</td><td>text</td></tr>
...
<tr><td>text</td><td>text</td></tr>
</table>

Now I want to add a javascript to the page that informs me of which row
I have clicked. If I click the second row it should fire an alert with
"You clicked row: 2". I don't want to add javascript inside the html of
the table.

Regards,

Roderik
 
M

Michael Winter

[snip]
Now I want to add a javascript to the page that informs me of which row
I have clicked.

That's fairly simple. The code below adds a click event listener to each
row in the "myTable" table. If the user clicks anywhere inside a row, the
click event will "bubble up" to the containing row.
If I click the second row it should fire an alert with "You clicked row:
2".

Just to point out: the rowIndex property used in the showRowNum() inner
function yields a zero-order index. That is, the second row will have the
index number, 1, hence the "+1" in the code.
I don't want to add javascript inside the html of the table.

That's OK. Call addRowListeners once the table has been parsed, either in
a SCRIPT element placed after the closing TABLE tag or, as in this
example, once the document has loaded.

function addRowListeners() {
/* Use this function as a common event listener for each row. */
function showRowNum() {
/* Check that the rowIndex property is
* supported before trying to use it.
*/
if('number' == typeof this.rowIndex) {
alert('You clicked row: ' + (this.rowIndex + 1));
}
}
/* Check that the getElementById method is
* supported before trying to use it.
*/
if(document.getElementById) {
/* Change the string, 'myTable', to reflect the actual id. */
var table = document.getElementById('myTable'), rows;
/* Ensure a reference was obtained and
* that we can access the rows.
*/
if(table && (rows = table.rows)) {
/* Add the listener to each row in the table. */
for(var i = 0, n = rows.length; i < n; ++i) {
rows.onclick = showRowNum;
}
}
}
}

<body ... onload="addRowListeners();">

Untested, but should work. Hope it helps,
Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top