Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select visual column in table with rowspan

I have seen a few similar questions but nothing that answers this specific problem. Consider the following table:

<table id="foo" border="1px">
    <tr>
        <td rowspan="2">one</td>
        <td>two</td>
        <td rowspan="2">three</td>
        <td>four</td>
        <td>five</td>
    </tr>
    <tr>
        <td rowspan="2">two</td>
        <td>four</td>
        <td>five</td>
    </tr>
    <tr>
        <td rowspan="2">one</td>
        <td>three</td>
        <td>four</td>
        <td>five</td>
    </tr>
    <tr>
        <td>two</td>
        <td>three</td>
        <td>four</td>
        <td>five</td>
    </tr>
</table>

Using jQuery, how can I select all items in a specific visual column? For example, if I want to select column 3, I should get all td's with 'three' as content.

like image 299
AdmSteck Avatar asked May 12 '11 16:05

AdmSteck


2 Answers

This plugin handles complex colspan and rowspan selection:

$('#foo th:nth-col(3), #foo td:nth-col(3)').css("color","red");
like image 127
utt73 Avatar answered Nov 15 '22 13:11

utt73


Haven't looked at the posted plugin, but I found the question interesting so I created a fiddle!

http://jsfiddle.net/PBPSp/

If the pluggin works it may be better than this, but it was a fun exercise so I may as well post it.

Change colToGet to whichever column you want to highlight.

$(function() {
    var colToGet = 2;

    var offsets = [];
    var skips = [];

    function incrementOffset(index) {
        if (offsets[index]) {
            offsets[index]++;
        } else {
            offsets[index] = 1;
        }
    }

    function getOffset(index) {
        return offsets[index] || 0;
    }

    $("#foo > tbody > tr").each(function(rowIndex) {

        var thisOffset = getOffset(rowIndex);

        $(this).children().each(function(tdIndex) {

            var rowspan = $(this).attr("rowspan");

            if (tdIndex + thisOffset >= colToGet) {
                if(skips[rowIndex]) return false;

                $(this).css("background-color", "red");

                if (rowspan > 1) {
                    for (var i = 1; i < rowspan; i++) {
                        skips[rowIndex + i] = true;
                    }
                }

                return false;
            }

            if (rowspan > 1) {
                for (var i = 1; i < rowspan; i++) {
                    incrementOffset(rowIndex + i);
                }
            }
        });
    });
});​
like image 32
James Montagne Avatar answered Nov 15 '22 15:11

James Montagne