DataTables

DataTables Examples

by TheOrdinaryGeek

HTML

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css">
<p class="text-center">
  <button type="button" id="resetFilter"> Reset Filters</button>
  <table border="0" cellspacing="5" cellpadding="5">
    <tbody>
      <tr>
        <td>Minimum age:</td>
        <td>
          <input type="text" id="min" name="min">
        </td>
      </tr>
      <tr>
        <td>Maximum age:</td>
        <td>
          <input type="text" id="max" name="max">
        </td>
      </tr>
    </tbody>
  </table>
  <table id="example" class="display" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
      </tr>
    </thead>

    <tfoot>
      <tr>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
      </tr>
    </tfoot>

    <tbody>
      <tr>
        <td>Tiger Nixon</td>
        <td>System Architect</td>
        <td>Edinburgh</td>
        <td>61</td>
        <td>2011/04/25</td>
        <td>$320,800</td>
      </tr>
      <tr>
        <td>Garrett Winters</td>
        <td>Accountant</td>
        <td>Tokyo</td>
        <td>63</td>
        <td>2011/07/25</td>
        <td>$170,750</td>
      </tr>
      <tr>
        <td>Ashton Cox</td>
        <td>Junior Technical...

JavaScript

/* Custom filtering function which will search data in column four between two values */
$.fn.dataTable.ext.search.push(
  function(settings, data, dataIndex) {
    var min = parseInt($('#min').val(), 10);
    var max = parseInt($('#max').val(), 10);
    var age = parseFloat(data[3]) || 0; // use data for the age column

    if ((isNaN(min) && isNaN(max)) ||
      (isNaN(min) && age <= max) ||
      (min <= age && isNaN(max)) ||
      (min <= age && age <= max)) {
      return true;
    }
    return false;
  }
);

$(document).ready(function() {
  var table = $('#example').DataTable();

  // Event listener to the two range filtering inputs to redraw on input
  $('#min, #max').keyup(function() {
    table.draw();
  });
  $('#resetFilter').click(function() {
    table
      .search('')
      .columns().search('')
      .draw();
    $('input[type=text]').val('').change();
  });
});