views:

289

answers:

3

I have a table in HTML which I am generating from XML/XSL and I want it to suppress repeating values. However, I also want to sort it on the fly by clicking the titles.

Without a round trip to the server I need to suppress different values after each sort. Is there a good javascript/css solution.

For example

Data

Date  Person Score  
May   Jeff   1  
May   Joel   2  
June  Alex   1

Initial Display
Note lack of second May

Date  Person Score  
May   Jeff   1  
      Joel   2  
June  Alex   1

Display After sorting by Score
Note lack of second 1

Date  Person Score  
May   Joel   2  
June  Alex   1
May   Jeff
A: 

Have a javascript function loop through the relevant table columns and remove the values that where the same as the ones before. You might also want to add a rowspan attribute to the first cell with that value so that the table' semantics are correct.

This isn't really a job for CSS as it's processing the information and not just displaying things (plus it'd be really hard).

edeverett
+2  A: 

Personally I would use something like jQuery Table Sorter. You can use the unique() function to remove duplicates as well. Using jQuery just makes doing things a lot easier than using JS. Either that or I would use JSF for my presentation layer, which already comes with functionality for just such occasions.

I don't really know of a "good" way to do it with JS. Every implementation in JS that I have ever seen is messy. Adding jQuery to you project will save you from having to write nasty JS code.

amischiefr
A: 

I would recommend setting a class on the td's with repeated values to hide them, so you don't lose the data. You can loop through each cell in the column, comparing it to the last one, and if it's the same, add the "duplicate" class to the cell.

function after_sort(sort_column) {
    clear_duplicate_classes();

    var last = null;
    for (var i = 0; i < trs.length; i++) {
        var td = get_nth_td(trs[i], sort_column);
        if (td.innerHTML === last) {
            add_duplicate_class(td);
        }
        else {
            last = td.innerHTML;
        }
    }
}

If you use a library like jQuery, it would look like this:

function after_sort(table, sort_column) {
    $(table).find(".duplicate").removeClass("duplicate");

    var last = null;
    $(table).find("tr").each(function() {
        var td = $(this).find("td").get(sort_column); // doesn't account for colspan
        if (td.innerHTML === last) {
            $(td).addClass("duplicate");
        }
        else {
            last = td.innerHTML;
        }
    });
}

These are totally untested, so I may have missed something. Use at your own risk, etc.

Matthew Crumley