jQuery DataTables

Example for article at https://www.gyrocode.com/articles/jquery-datatables-how-to-search-and-order-by-input-or-select-elements/

by Shrikrishna Gupta

HTML

<link rel="stylesheet" href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<script src="//cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<h3>jQuery DataTables: How to search and order by INPUT or SELECT elements</h3>

<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>
         <th>Vehicle</th>
      </tr>
   </thead>
   <tfoot>
      <tr>
         <th>Name</th>
         <th>Position</th>
         <th>Office</th>
         <th>Age</th>
         <th>Start date</th>
         <th>Salary</th>
         <th>Vehicle</th>
      </tr>
   </tfoot>
   <tbody>
      <tr>
         <td>Tiger Nixon</td>
         <td><input type="text" value="System Architect"></td>
         <td>Edinburgh</td>
         <td>61</td>
         <td>2011/04/25</td>
         <td>$320,800</td>
         <td>
            <select>
               <option value="volvo" selected>Volvo</option>
               <option value="saab">Saab</option>
               <option value="mercedes">Mercedes</option>
               <option value="audi">Audi</option>
            </select>
         </td>
      </tr>
      <tr>
         <td>Airi Satou</td>
         <td><input type="text" value="Accountant"></td>
         <td>Tokyo</td>
         <td>33</td>
         <td>2008/11/28</td>
         <td>$162,700</td>
         <td>
            <select>
               <option value="volvo">Volvo</option>
               <option value="saab">Saab</option>
               <option value="mercedes" selected>Mercedes</option>
               <option value="audi">Audi</option>
            </select>
         </td>
      </tr>
      <tr>
         <td>Garrett Winters</td>
         <td><input type="text" value="Accountant"></td>
         <td>Tokyo</td>
         <td>63</td>
         <td>2011/07/25</td>
         <td>$170,750</td>
      ...

JavaScript

$(document).ready(function (){
   var table = $('#example').DataTable({
      columnDefs: [
         { 
            targets: [1, 6], 
            type: 'string',
            render: function(data, type, full, meta){
               if (type === 'filter' || type === 'sort') {
                  var api = new $.fn.dataTable.Api(meta.settings);
                  var td = api.cell({row: meta.row, column: meta.col}).node();
                  data = $('select, input[type="text"]', td).val();
               }

               return data;
            }
         }
      ]
   });
   
   $('#example').on('change', 'tbody select, tbody input[type="text"]', function(){
      table.cell($(this).closest('td')).invalidate();
      
      // Redraw table (optional)
      // table.draw(false);
   });    
});