Checkbox Parser and Bug Fix for jQuery TableSorter Plugin

by Bill Beckelman 24. October 2008 01:26

I wanted to pass along a few things I have run into with the jquery tablesorter plugin that might help those of you who have been following my recent posts:

 

  1. I wanted to be able to sort by a column of checkboxes but the plugin doesn't support it out of the box. Luckily the plugin is structured so that you can add your own parsers. I found a parser here to take care of sorting checkboxes. I think it was meant for an older version of the tablesorter plugin so I changed a few things to make it work with version 2.0.3.  Just add the code below to the list of parsers in the plugin.
        /*
        * Extra parser: checkbox
        * Credit: Christian Bach
        * Modified By Bill Beckelman
        */
        ts.addParser({
            id: 'input',
            is: function(s) {
                return s.toLowerCase().match(/<input[^>]*checkbox[^>]*/i); ;
            },
            format: function(s) {
                var integer = 0;
                if (s.toLowerCase().match(/<input[^>]*checked*/i)) {
                    integer = 1;
                }
                return integer;
            },
            type: "numeric"
        });    
  2. There is a bug when sorting numbers when the first item in the table is a "0". The numbers are interpreted as text instead of digits and you will end up with a sequence like 1, 10, 2, 3, 31 etc. I found the solution in this jquery mailing list thread which uses a different regular expression in the isDigit function in the tablesorter.js plugin.
            this.isDigit = function(s, config) {
                var exp= '/(\0)|(^[+]?0(\.0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)\.([0-9]*)))$)|(^[-+]?[1-9]+[0-9]*\.0+$)/';
                return RegExp(exp).test($.trim(s.replace(/,/g, '')));

                //Has bug when 0 is first digit in list and interprets as text.
                //http://groups.google.com/group/jquery-dev/browse_thread/thread/d8e75a30f7ca3067                        
                //var DECIMAL = '\\' + config.decimal;
                //var exp = '/(^[+]?0(' + DECIMAL + '0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)' + DECIMAL + '(0*[1-9][0-9]*)))$)|(^[-+]?[1-9]+[0-9]*' + DECIMAL + '0+$)/';
                //return RegExp(exp).test($.trim(s));
            };

 

I hope these finds help you. Let me know if you find any other issues with the plugin or improve it in anyway.

     kick it on DotNetKicks.com

 

Tags:

jQuery

Comments


About Me

I live and work in Salt Lake City, Utah. My background is in aviation. I have a degree in Aeronautical Science from Embry-Riddle Aeronautical University in Prescott, AZ. I have worked as a commercial airline pilot and most recently as a technical advisor for a charter airline.