javascriptjqueryhtml-tableonclickrow

Get row index of clicked button properly


I've tried several ways to get the row index of a clicked button inside a table.

The table:

while ($info = mysqli_fetch_array($sql)) {
    echo "<tr>";
        echo "<th>{$info['name']}</th>";
        echo "<th>{$info['pass']}</th>";
        echo "<th><a href='http://{$info['link']}'>{$info['link']}</a></th>";
        echo "<th><div class='delbuttons'><button class='btn btn-info' data-toggle='modal' data-target='#myModal' id='{$info['id']}'>Delete</button></div></th>";
    echo "</tr>";
}
?>

These are the ways that I've tried:

$(document).on('click', '.delbuttons button', function(event) {
    alert($(this).index());
}

but it always returns -1.

$(document).on('click','.delbuttons button', function(event) {
    alert(this.rowIndex);
}

This returns undefined.


Solution

  • Your issue is in this line:

    alert($(this).index());
    

    According to the documentation:

    .index(): Search for a given element from among the matched elements.

    Because your button is the unique element contained in the div the correspondig result will be always 0.

    In order to get the row index, instead, it is sufficient to get the index of the closest tr:

    $(this).closest('tr').index()
    

    In your second approach you try to get the rowIndex of the clicked button. But this attribute is related only to a table row element. Hence, in this case you will get undefined.

    $(document).on('click','.delbuttons button', function(event) {
        console.log($(this).closest('tr').index());
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <table>
        <tr>
            <td>name1</td>
            <td>pass1</td>
            <td><a href="http://xxx">xxx</a></td>
            <td>
                <div class="delbuttons">
                    <button class="btn btn-info" data-toggle="modal" data-target="#myModal" id="id1"> Delete</button>
                </div>
            </td>
        </tr>
        <tr>
            <td>name2</td>
            <td>pass2</td>
            <td><a href="http://xxx">xxx</a></td>
            <td>
                <div class="delbuttons">
                    <button class="btn btn-info" data-toggle="modal" data-target="#myModal" id="id2"> Delete</button>
                </div>
            </td>
        </tr>
        <tr>
            <td>name3</td>
            <td>pass3</td>
            <td><a href="http://xxx">xxx</a></td>
            <td>
                <div class="delbuttons">
                    <button class="btn btn-info" data-toggle="modal" data-target="#myModal" id="id3"> Delete</button>
                </div>
            </td>
        </tr>
    </table>