mrras
mrras

Reputation: 462

How to set first click sort to descending in google charts table

I have a google charts table full of data. Right now when a user tries to sort the table (by clicking on one of the column's header) the data is being sorted ascending, and a second click sorts the data again, this time descending. I want to reverse this behavior, and have the first click on a 'not-previously-sorted' column a descending sort, and the second click an ascending sort.

For example, in this http://jsfiddle.net/wrebr0ze/ the first click on the "Salary" header should make $12,500 appear on top. first click on "Name" header should make Mike appear on top.

I tried looking at the sort event, but although I can catch it, I do not want to sort the data myself, just want to make it trigger the right action. I looked at the api for such option but with no luck, sortAscending only works for the initial sort (before the data shows), not later.

Upvotes: 2

Views: 1239

Answers (1)

juvian
juvian

Reputation: 16068

Unfortunately there is not an easy way to reverse this behaviour. Still, here is a workaround using the sort event:

var sorting={};
function drawTable() {
// ...code
       var table = new google.visualization.Table(document.getElementById('table_div'));

      google.visualization.events.addListener(table, 'sort', function(e){
      if(!sorting.hasOwnProperty('column')){
          sorting=e;
      }
      if(sorting.column==e.column){
          sorting.desc=sorting.ascending;
          sorting.ascending=!sorting.ascending;
      }else{
          sorting.desc=true;
          sorting.ascending=false;
          sorting.column=e.column;
      }    
      data.sort([sorting]);
      table.draw(data, {showRowNumber: true});
      })
      table.draw(data, {showRowNumber: true, sortAscending: false});

Full fiddle: http://jsfiddle.net/wrebr0ze/1/

Upvotes: 2

Related Questions