Search code examples
ruby-on-railstablesorter

tablesorter to sort columns which has <br> within them


I have a table which has one of the column's as datetime: eg: 1/11/2011 12:34 PM

Unfortunately, the width of the column does not allow me to display datetime in full length in one line, hence I am displaying the contents in two lines, like

   1/11/2011
   12:34 PM

But tablesorter will not work if the column contents have a <br> in them. Any idea how I can achieve sorting via tablesorter for this issue? I am having tablesorter revision 2.0.5b. I cannot upgrade to newer version because it might break existing features of the rails app.

tablesorter is the jquery plugin


Solution

  • You'll probably need a custom parser to remove the carriage return; honestly, I don't think a <br> needs to be added if the text is allowed to wrap, and you set a width for that column.

    Anyway, try this code (demo)

    $(function () {
    
        $.tablesorter.addParser({
            // set a unique id
            id: 'date',
            is: function (s, table, cell) {
                // return false so this parser is not auto detected
                return false;
            },
            format: function (s, table, cell, cellIndex) {
                // replace extra spacing/carriage returns
                var str = s.replace(/\s+/g," "),
                    date = new Date( str );
                return date instanceof Date && isFinite(date) ? date.getTime() : s;
            },
            // set type, either numeric or text
            type: 'numeric'
        });
    
        $('table').tablesorter({
            theme: 'blue',
            headers: {
                7: { sorter: 'date' }
            }
        });
    });