Tags

Mootools provides a great HtmlTable for display and sorting and everything else you want. Document is sparse for such a good utility.

And today, yours truly discovered that custom sorting is not a well documented feature. Maybe I was being stupid.

Anyway, let’s say you want to sort a table like the one below. Note, we use plain string, numbers and range.

Name Region Expected Returns Number of sec. held
North American Fund Americas 15% 15 – 20
European Growth EMEA 16% >50
Greater China Equities Asia/Pacific 13% <20
Australian Value Asia/Pacific 14% 40 – 60
Global Reach Global 18% 15 – 30
Money Market Value Global 14% 80
Absolute Growth Global 3% 35 – 55
Alternative Investments Americas 21% >60
  • Here’s the code for setting up the table as per official documentation.
  • var myTable = new HtmlTable({
      properties: {
        border: 1,
        cellspacing: 3
      },
      rows: [
        ['apple', 'red'],
        ['lemon', 'yellow']
      ]
    });
    myTable.inject($('someContainer'));
    
  • Now we add parsers to the official documentation
  • 
    function parseNumberofSecurities(){
    	//We will add parsing logic here later.
    }
    
    //make sure that the length is equal
    //   to the number of columns.
    //Leave null for columns
    //   that you want Mootools to decipher.
    var customParsers = [null, null, null
    	, parseNumberofSecurities];
    
    var myTable = new HtmlTable({
      properties: {
        border: 1,
        cellspacing: 3
      },
      rows: [
        ['apple', 'red'],
        ['lemon', 'yellow']
      ],
      parsers: customParsers,
      sortable: true
    });
    myTable.inject($('someContainer'));
    
  • Implementation of parser.
  • var securities;
    var parsedSec;
    function parseSecuritiesHeld(){
    	securities = this.get('text');
    
    	if(securities.charAt(0)=='<'){
    		parsedSec = parseInt( securities.replace(''){
    		parsedSec = parseInt( securities.replace('>','') );
    		return parsedSec+0.01;
    	}
    
    	var index = securities.indexOf('-');
    	if(index>0){
    		//This is a range.
    		//As we will only have whole numbers, replace hyphen with dot.
    		parsedSec = parseFloat( securities.replace(' - ','.') );
    		return parsedSec;
    	}
    
    	//This is just a number.
    	return parseInt( securities);
    }