Skip to content Skip to sidebar Skip to footer

How Do I Sort Table From Dropdown List

How do I create a simple sorting function for this. I know there is plugin like tablesorter. But it doesn't sort it from a dropdown list. Or is the plugin can be modified so that i

Solution 1:

Sorting the table is fairly easy to do yourself, all you'd have to do is sort the rows using javascript's sort method (http://www.w3schools.com/jsref/jsref_sort.asp) and re-adding the rows to the table.

You could create sorting methods for different data-types like:

functionsortByNumber(rows, selector, ascending) {
  rows.sort(function(a, b) {
    var numberA = parseInt($(selector, a).text(), 10);
    var numberB = parseInt($(selector, b).text(), 10);

    if (ascending)
      return numberA - numberB;
    elsereturn numberB - numberA;
  });

  return rows;
}

functionsortByText(rows, selector, ascending) {
  rows.sort(function(a, b) {
    var textA = $(selector, a).text();
    var textB = $(selector, b).text();

    if (ascending)
      return textA.localeCompare(textB);
    elsereturn textB.localeCompare(textA);
  });

  return rows;
}

(working example at https://jsfiddle.net/kg000ta7/)

However, if you plan to have a lot of rows or columns in your table, a plugin like tablesorter will probably perform better.

According to the documentation you are able to manually sort tablesorter by triggering the 'sorton' event: http://tablesorter.com/docs/example-trigger-sort.html

$('select').on('change', function() {
  var sorting;

  switch (field) {
    case 'ID':
      sorting = [[0,0]];
      break;
    case 'Name':
      sorting = [[1,0]];
      break;
    case 'Occupation':
      sorting = [[2,0]];
      break;
    default:
      console.error('Undefined sort field ' + field);
      break;
  }

  $("table").trigger("sorton",[sorting]); 
  returnfalse; 
});

Post a Comment for "How Do I Sort Table From Dropdown List"