TransWikia.com

Jquery datatables inbuilt sort is not working

Stack Overflow Asked by Karthik on January 12, 2021

Inbuilt datatable column sort is not working. On clicking header in any column, it displays 0 rows.

I have tried using aasorting, columndefs, orderable which worked for others, but it didnt work in my case.

I figured out that column sort is not working due to $.fn.dataTable.ext.search.push() function because as I comment it out, column sorting works, which means some dependency is getting created due to that function. But its part of code so cant remove it out. Please provide suggestions to make this work.

var table = $('#example').DataTable({
  "bLengthChange": false,
  //searching: false,
  pageLength: 3,
  dom: 'tip'
});
  
$.fn.dataTable.ext.search.push(function( settings, data, dataIndex ) {
    
    var filterCategory= $("#cato option:selected").text().toUpperCase();
    var filterSubCategory= $("#subo option:selected").text().toUpperCase();
    var subCategory = String(data[2]).toUpperCase();
    var category = String(data[3]).toUpperCase();
    
    if(filterSubCategory != "-SELECT SUBCATEGORY-") {
        if ( filterCategory == category && filterSubCategory == subCategory)
             return true;
        }
        else if(filterCategory != "-SELECT CATEGORY-") {
            if ( filterCategory == category)
             return true;
        }        
        return false;
    }
);

$('#cato').on('change', function() {
  $('#subo').val("");
  table.draw();
});

$('#subo').on('change', function() {
  table.draw();
});

function getInfo() {
        var $subCategory = $("#subo option:selected").text()
        $.ajax({
      type:'GET',
      url: "https://my-json-server.typicode.com/SagnalracSO/repo/items?subcategory=" + $subCategory,
      dataType: "json",
      beforeSend: function(jqXHR, settings) {   
          if($subCategory.toUpperCase() == '-SELECT SUBCATEGORY-') {
              alert('Select a SubCategory');
                jqXHR.abort();
          }
      },
      success: function(data) {      
        var item = data[0];
        var jRow = $("<tr>").append("<td>" + item.id + "</td><td>" + item.product + "</td><td>" + item.subcategory + "</td><td>" + item.category + "</td>").append("</tr>");
        table.row.add(jRow).draw();
      }
   });
}
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>

<select id="cato" class="form-control" >
  <option value="" disabled selected="true">-Select Category-</option>
  <option>Electronics</option>
  <option>Sports</option>
</select>

<select id="subo" class="form-control">
   <option value="" disabled selected="true">-Select Subcategory-</option>
   <option>Laptop</option>
   <option>Mobile</option>
</select>

<table id="example" class="table display">
  <thead>
    <tr>
      <th>Id</th>
      <th>Product</th>
      <th>Subcategory</th>
      <th>Category</th>
    </tr>
  </thead>
  <tbody id="r">
    <tr>
      <td>1</td>
      <td>Samsung</td>
      <td>Mobile</td>
      <td>Electronics</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Racket</td>
      <td>Tennis</td>
      <td>Sports</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Bat</td>
      <td>Cricket</td>
      <td>Sports</td>
    </tr>
    <tr>
      <td>4</td>
      <td>Dell</td>
      <td>Laptop</td>
      <td>Electronics</td>
    </tr>
    <tr>
      <td>5</td>
      <td>Iphone</td>
      <td>Mobile</td>
      <td>Electronics</td>
    </tr>
    <tr>
      <td>6</td>
      <td>Soccer Ball</td>
      <td>Soccer</td>
      <td>Sports</td>
    </tr>
  </tbody>
</table>
<br><br>
<input type="button" value="ADD ROWS" onClick="getInfo()" />

One Answer

I forgot to include the scenario where none of the filters is set (and also I didn't know that sorting fires the search.push functionality).

All you have to do is return true when there is no filter at all. For example, in your case I just added a couple of lines:

if(filterSubCategory == "-SELECT SUBCATEGORY-" && filterCategory == "-SELECT CATEGORY-")
        return true;

var table = $('#example').DataTable({
  "bLengthChange": false,
  //searching: false,
  pageLength: 3,
  dom: 'tip'
});
  
$.fn.dataTable.ext.search.push(function( settings, data, dataIndex ) {
    
    var filterCategory= $("#cato option:selected").text().toUpperCase();
    var filterSubCategory= $("#subo option:selected").text().toUpperCase();
    var subCategory = String(data[2]).toUpperCase();
    var category = String(data[3]).toUpperCase();
    
    if(filterSubCategory == "-SELECT SUBCATEGORY-" && filterCategory == "-SELECT CATEGORY-")
        return true;
    else if(filterSubCategory != "-SELECT SUBCATEGORY-") {
        if ( filterCategory == category && filterSubCategory == subCategory)
             return true;
        }
        else if(filterCategory != "-SELECT CATEGORY-") {
            if ( filterCategory == category)
             return true;
        }        
        return false;
    }
);

$('#cato').on('change', function() {
  $('#subo').val("");
  table.draw();
});

$('#subo').on('change', function() {
  table.draw();
});

function getInfo() {
        var $subCategory = $("#subo option:selected").text()
        $.ajax({
      type:'GET',
      url: "https://my-json-server.typicode.com/SagnalracSO/repo/items?subcategory=" + $subCategory,
      dataType: "json",
      beforeSend: function(jqXHR, settings) {   
          if($subCategory.toUpperCase() == '-SELECT SUBCATEGORY-') {
              alert('Select a SubCategory');
                jqXHR.abort();
          }
      },
      success: function(data) {      
        var item = data[0];
        var jRow = $("<tr>").append("<td>" + item.id + "</td><td>" + item.product + "</td><td>" + item.subcategory + "</td><td>" + item.category + "</td>").append("</tr>");
        table.row.add(jRow).draw();
      }
   });
}
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>

<select id="cato" class="form-control" >
  <option value="" disabled selected="true">-Select Category-</option>
  <option>Electronics</option>
  <option>Sports</option>
</select>

<select id="subo" class="form-control">
   <option value="" disabled selected="true">-Select Subcategory-</option>
   <option>Laptop</option>
   <option>Mobile</option>
</select>

<table id="example" class="table display">
  <thead>
    <tr>
      <th>Id</th>
      <th>Product</th>
      <th>Subcategory</th>
      <th>Category</th>
    </tr>
  </thead>
  <tbody id="r">
    <tr>
      <td>1</td>
      <td>Samsung</td>
      <td>Mobile</td>
      <td>Electronics</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Racket</td>
      <td>Tennis</td>
      <td>Sports</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Bat</td>
      <td>Cricket</td>
      <td>Sports</td>
    </tr>
    <tr>
      <td>4</td>
      <td>Dell</td>
      <td>Laptop</td>
      <td>Electronics</td>
    </tr>
    <tr>
      <td>5</td>
      <td>Iphone</td>
      <td>Mobile</td>
      <td>Electronics</td>
    </tr>
    <tr>
      <td>6</td>
      <td>Soccer Ball</td>
      <td>Soccer</td>
      <td>Sports</td>
    </tr>
  </tbody>
</table>
<br><br>
<input type="button" value="ADD ROWS" onClick="getInfo()" />

Happy Coding!

Correct answer by Sagnalrac on January 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP