简体   繁体   中英

Sort html table rows by first date column with jQuery

I have table with two date columns in each row start date and end date I want to sort table rows by start date with jQuery

Below is the table html code:

<table class="table-bordered">
  <thead>
    <tr class="Headers">
      <th>Number</th>
      <th>Date Start</a></th>
      <th>Date End</th>
    </tr>
  </thead>
  <tbody>
    <tr class="Entries" data-id="13">
      <td data-field-type="string">1234</td>
      <td data-field-type="date">01-04-2015</td>
      <td data-field-type="date">01-04-2015</td>
    </tr>
    <tr class="Entries" data-id="24">
      <td data-field-type="string">1352</td>
      <td data-field-type="date">04-10-2012</td>
      <td data-field-type="date">23-10-2015</td>
    </tr>
    <tr class="Entries" data-id="8">
      <td data-field-type="string">1124</td>
      <td data-field-type="date">13-05-2014</td>
      <td data-field-type="date">01-04-2015</td>
    </tr>
    <tr class="Entries" data-id="23">
      <td data-field-type="string">1652</td>
      <td data-field-type="date">07-11-2013</td>
      <td data-field-type="date">22-10-2015</td>
    </tr>
  </tbody>
</table>

I made a try with similar solution posted here but without success. JSFiddle

Look at this site. It looks like this is what you are trying to do. http://www.kryogenix.org/code/browser/sorttable/

when you pass string to Date constructor it's format is month/date/year .

since your date format is date-month-year . you can reformat it using regular expression.

$('tr.Entries').sort(function (a, b) {
    return new Date($(a).find($("[data-field-type='date']")).html().replace(/(\d{2})-(\d{2})-(\d{2})/g,'$2/$1/$3')).getTime() < new Date($(b).find($("[data-field-type='date']")).html().replace(/(\d{2})-(\d{2})-(\d{2})/g,'$2/$1/$3')).getTime()
}).appendTo('tbody');

I'd suggest:

$('tr.Entries').each(function() {
     var t = this.cells[1].textContent.split('-');
     $(this).data('_ts', new Date(t[2], t[1]-1, t[0]).getTime());
}).sort(function (a, b) {
    return $(a).data('_ts') < $(b).data('_ts');
}).appendTo('tbody');

http://jsfiddle.net/rmva17gr/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM