get row number in table

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Roderik

    #1

    get row number in table

    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
  • Michael Winter

    #2
    Re: get row number in table

    On Tue, 02 Nov 2004 03:37:10 +0100, Roderik <mail@roderik.n et> wrote:

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

    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.
    [color=blue]
    > If I click the second row it should fire an alert with "You clicked row:
    > 2".[/color]

    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.
    [color=blue]
    > I don't want to add javascript inside the html of the table.[/color]

    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.get ElementById) {
    /* Change the string, 'myTable', to reflect the actual id. */
    var table = document.getEle mentById('myTab le'), 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[i].onclick = showRowNum;
    }
    }
    }
    }

    <body ... onload="addRowL isteners();">

    Untested, but should work. Hope it helps,
    Mike

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.

    Comment

    Working...