jQuery DataTables: How to search and order by INPUT or SELECT elements

Problem

When there is INPUT or SELECT element present in the table cell, DataTables plug-in ignores its value during searching or ordering.

Solution

  1. To make DataTables aware of the actual value of the SELECT or INPUT element, we can dynamically generate cell content for various operations. This can be done by returning element’s value in a callback defined by columnDefs.render option for filtering (type equals to filter) and searching (type equals to sort) operations.

    To prevent DataTables from incorrectly detecting cell content as HTML, we need to set cell type to string using columnDefs.type option.

    
       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;
                }
             }
          ]
       });
    
  2. Another potential problem is that DataTables plugin caches dynamically produced cell content produced by callback defined by columnDefs.render option. In order to let DataTables know that value of INPUT or SELECT element has changed, we need to invalidate cell content, by using one of the invalidate() API methods, for example cell().invalidate().

    If you want to update search results, once INPUT or SELECT elements have been changed, add call to to redraw the table table.draw(false) after invalidating the cell content.

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

Example

  1. Search Volvo to locate Tiger Nixon.
  2. Change Volvo to Audi and attempt to search for Volvo again.

See Also

You May Also Like

Leave a Reply

You may use simple HTML to add links or lists to your comment. Also use <pre><code class="language-*">...</code></pre> to mark up code snippets. We support language-js, language-markup and language-css for comments.
(Optional)

This site uses Akismet to reduce spam. Learn how your comment data is processed.