Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Count number/Get Index of rowspan rows

I'm trying to figure out how to get the index of the current rowspanned "row" (even though its the cell that is rowspanned).

<table>
    <tr>
        <td rowspan="2">First</td>
        <td> First 1 1 </td>
        <td> First 2 1 </td>
    </tr>
    <tr>
         <td> First 2 1 </td>
         <td> First 2 2 </td>
    </tr>
    <tr>
        <td rowspan="2">Second</td>
        <td> Second 1 1 </td>
        <td> Second 2 1 </td>
    </tr>
    <tr>
         <td> Second 2 1 </td>
         <td> Second 2 2 </td>
    </tr>
</table>

If I clicked on any cell in the table, how can I count which "row-spanned" row I'm at?

For example if I click on any of the "Second" cells, I should get "2" and if I click on any of the "First" cells, I should get "1".

I've tried multiple things include this:

row=$(this).parent().parent().children('tr').filter(function (index) {
    return $(this).children('td[rowspan]'); }).index($(this).parent());

and

row=$(this).parent().parent().children('tr:contains("td[rowspan]")')
    .parent().parent().index($(this).parent());

and sort-of got it to work with

$row=$(this).parent();
while ($row.children('td:eq(0)').attr("rowspan").length<=0)
    $row=$row.prev();
span=$row.children('td:eq(0)').attr("rowspan");
row=Math.floor( parseInt($(this).parent().parent().children().index( $(this).parent()) )/span );

but this will only work give that there is a rowspan cell... and is assuming that all rows have that same rowspan

I tried working off these site, but couldn't get too far.


jquery selector to count the number of visible table rows?
JQuery: How to select rows from a table
Table row and column number in jQuery

like image 765
jao Avatar asked Feb 20 '23 01:02

jao


1 Answers

One way is to build an array from the rowspan attributes of the cells in the first column. From there, you can get the index of the clicked row and iterate over the rowspan array, subtracting the extents of the spans as you go. Once you go below zero, you have your (zero-based) index:

$("td").click(function() {
    var $this = $(this);
    var rowIndex = $this.closest("tr").index();
    $this.closest("table").find("tr").map(function() {
        return $(this).find("td:first").attr("rowspan") || 1;
    }).each(function(index) {
        if ((rowIndex -= this) < 0) {
            alert(index + 1);  // 'index' is zero-based.
            return false;
        }
    });
});

You can test it in this fiddle.

like image 98
Frédéric Hamidi Avatar answered Mar 05 '23 03:03

Frédéric Hamidi