javascript - jQuery sort HTML tables with custom order -


i want able sort tables month.

example:

february december october august july 

when sorted should be

february july august october  december 

i've experimented few jquery plugins online , none of them had option create custom sort order.

thanks!

let's immagine add attribute each table row called sort-order.

now, can order table according attribute:

$(function () {    // sort table rows    var sortedtablerows = $('table tbody tr').get().sort(function (a, b) {      var aval = +a.getattribute('sort-order');      var bval = +b.getattribute('sort-order');      return (aval > bval) ? 1 : (aval < bval) ? -1 : 0;    });        // substitute table rows ordered 1    $.each(sortedtablerows, function (i, e) {      $('table tbody').append(e);    });  });
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>    <table>      <thead>      <th>          <tr>              <td>months</td>          </tr>      </th>      </thead>      <tbody>      <tr sort-order="12">          <td>january</td>      </tr>      <tr sort-order="11">          <td>february</td>      </tr>      <tr sort-order="10">          <td>march</td>      </tr>      <tr sort-order="9">          <td>april</td>      </tr>      <tr sort-order="8">          <td>may</td>      </tr>      <tr sort-order="7">          <td>june</td>      </tr>      <tr sort-order="6">          <td>july</td>      </tr>      <tr sort-order="5">          <td>august</td>      </tr>      <tr sort-order="4">          <td>september</td>      </tr>      <tr sort-order="3">          <td>october</td>      </tr>      <tr sort-order="2">          <td>november</td>      </tr>      <tr sort-order="1">          <td>december</td>      </tr>      </tbody>  </table>


Comments