skip to Main Content

I have datatable on html page.In my Datatable I have column wise search at footer. This search is working for all column but one column have select- option element (dropdown) for this it is not working. every time when it start searching instead of selected value of list, it is searching on all list value.

This my table looks like :-
enter image description here

here you can see position search is working fine. its draw match value correctly.
enter image description here

Salary column having list value that contains :- Adapter,Adater1,capacitor, diode
but here when i try to search it will not search on selected value, it search on whole list for each rows, thats why when i type Adapter1 it will not able to segregate because every row having Adapter1 as a value. ideally it should show only one row but here is my output :-

enter image description here

But when i type any value which is not present in list then it show correctly, So search is working but it takes all value instead of selected value :-
enter image description here

can you please help me on this.

Below is my Code

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BootStrap</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> -->

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-table.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.3.4/css/select.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://editor.datatables.net/extensions/Editor/css/editor.dataTables.min.css">

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/datetime/1.1.2/css/dataTables.dateTime.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css">
<!-- <link type="text/css" href="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/css/dataTables.checkboxes.css" rel="stylesheet" /> -->
<!-- https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css -->
</head>
<body>

<div class="container mb-3 mt-3">

<div class="panel panel-default">
  <div class="panel-heading"><b> Demo </b> </div>

  <div class="panel-body">
    
    <div class="tbl_user_data"><table class="table table-striped table-bordered" id = "mydatatable"
>

<thead>
           <tr>
           <th></th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
</thead>
<tbody>
            <tr row_id = "123">
            <td></td>
                <td><div class="row_data" edit_type="click" col_name="fname">Tiger Nixon</div></td>
                <td><div class="row_data" edit_type="click" col_name="pos">Developer</div></td>
                <td><div class="row_data" edit_type="click" col_name="off">Edinburgh</div></td>
                <td><div class="row_data" edit_type="click" col_name="age">61</div></td>
                <td><div class="row_data" edit_type="click" col_name="startdate">2011/04/25</div></td>
                <td><div class="row_data" edit_type="lov" col_name="sal">
                <select class="example-dropUp" id="selhw">
                <option >Adapter</option>
                <option selected>Adapter1</option>
                <option >Capacitor</option>
                 <option >Diode</option>
                </select>
                </div></td>
            </tr>
                        <tr row_id = "124">
            <td></td>
                <td><div class="row_data" edit_type="click" col_name="fname">Tiger Nixon1</div></td>
                <td><div class="row_data" edit_type="click" col_name="pos">System Architect1</div></td>
                <td><div class="row_data" edit_type="click" col_name="off">Edinburgh1</div></td>
                <td><div class="row_data" edit_type="click" col_name="age">611</div></td>
                <td><div class="row_data" edit_type="click" col_name="startdate">2011/04/25</div></td>
                <td><div class="row_data" edit_type="lov" col_name="sal">
                <select class="example-dropUp" id="selhw">
                <option >Adapter</option>
                <option >Adapter1</option>
                <option selected>Capacitor</option>
                 <option >Diode</option>
                </select>
                </div></td>
            </tr>
                        <tr row_id = "125">
            <td></td>
                <td><div class="row_data" edit_type="click" col_name="fname">Tiger Nixon2</div></td>
                <td><div class="row_data" edit_type="click" col_name="pos">System Architect2</div></td>
                <td><div class="row_data" edit_type="click" col_name="off">Edinburgh2</div></td>
                <td><div class="row_data" edit_type="click" col_name="age">61</div></td>
                <td><div class="row_data" edit_type="click" col_name="startdate">2011/04/25</div></td>
                <td><div class="row_data" edit_type="lov" col_name="sal">
                <select class="example-dropUp" id="selhw">
                <option >Adapter</option>
                <option >Adapter1</option>
                <option >Capacitor</option>
                 <option selected>Diode</option>
                </select>
                </div></td>
                               <tfoot>
            <tr>
            <th></th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
        </tbody>
</table>
  </div>
</div>
</div>

 

<div class="panel panel-default">
  <div class="panel-heading"><b>HTML Table Edits/Upates</b> </div>

  <div class="panel-body">
    
    <p>All the changes will be displayed below</p>
    <div class="post_msg"> </div>

  </div>

 
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/esm/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/select/1.3.4/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="/js/bootstrap-table.min.js"></script>
<script src="https://editor.datatables.net/extensions/Editor/js/dataTables.editor.min.js"></script>
<script src="https://cdn.datatables.net/datetime/1.1.2/js/dataTables.dateTime.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>





<!-- <script type="text/javascript" src="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/js/dataTables.checkboxes.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function($)
{

     $('#mydatatable tfoot th').each( function (index) {
            //alert("in Tfoot");
            console.log("tfoot th");
             var title = $(this).text();
             var notapplyFilteronColumn =[0]
             if(notapplyFilteronColumn.indexOf(index) < 0 )
                {
                         $(this).html( '<input type="text" id="txtName'+index+'" placeholder="Search '+title+'" data-index="'+index+'" />' );
                }
         } );

 var table = $('#mydatatable').DataTable({
        order:[[3,'desc']],
//      processing: true,
        pagingType:'full_numbers',
         pageLength:20,
         scrollY:500,
         scrollX:true,
         searchable: true,
        // bFilter: false,
        lengthMenu:[[5,10,25,50,-1],[5,10,25,50,"All"]],    
         select: {
             style: 'multi'
         },
         columnDefs: [ {
             orderable: false,
             className: 'select-checkbox',
             targets:   0,
         }
         ],

         select: {
             style:    'multi',
             selector: 'td:first-child'
         },
         search:
             {
             caseInsensitive: true,
             smart: true
             },
         order: [[ 1, 'asc' ]],
        
         initComplete: function () {
             // Apply the search
       console.log("Inside initcomplete");
                this.api().columns().every( function (index) {          
                  var that = this;  
                 $( 'input', this.footer() ).on( 'keyup change clear', function () {
                     console.log("inside Keyup change");
                     console.log("index = "+index);
                if ( that.search() !== this.value ) {
                         that
                             .search(this.value)
                             .draw();
                     }  
                
                 } );    
                 
             } );
                

         }   //initcomplete


         
     }); //dt

    

}); 

</script>


</body>
</html>

2

Answers


  1. When you use the search(...) API call in this way, you are limited to searching all content in each column. In your case, there are two problems with this:

    (1) Each cell containing a select list actually contains the full HTML text of the <select>...</select> element – including all the options used by the select. This is why the search does not appear to work. It is, in fact, working correctly. It will always find every select option, regardless of whether it is the selected option.

    (2) A user can choose any select option at any time – and all such changes are only captured in the DOM. The underlying DataTable (i.e. the JavaScript object) does not know anything about such changes. So, there is no straightforward way to tell the DataTables search() function about such changes.

    Solution

    One solution is to create a custom DataTables search function using $.fn.dataTable.ext.search. You can see a basic example here.

    Below is a runnable snippet based on a simplified version of the code in your question, showing how to adapt $.fn.dataTable.ext.search to also handle a column containing select lists:

    // remove the default global filter function:
    while($.fn.dataTable.ext.search.length > 0) {
      $.fn.dataTable.ext.search.pop();
    }
    
    // add our custom filter function:
    $.fn.dataTable.ext.search.push(
      function( settings, data, rowIdx ) {
        // get the TD node containing the drop-down list:
        var selectListTdNode = $('#example').DataTable().rows(rowIdx).nodes().to$().find( 'td' )[5]
        // get the selected value:
        var selection = $( selectListTdNode ).find(":selected").text();
        
        // process each field in the row:
        var displayRow = true; // start by assuming the row should be displayed
        data.forEach(function (item, idx) {
          // for the 6th column (idx = 5), we need to use the selected drop-down
          //  value, and not the contents of the cell:
          item = (idx === 5) ? selection : item;
          
          var searchField = $('#example').DataTable().columns(idx).footer();
          var searchValue = $(searchField).find( 'input' ).val();
          // should the row be displayed? 'false' means 'do not display':
          if (searchValue !== '' & !item.toLowerCase().includes(searchValue.toLowerCase())) {
            displayRow = false;
          }
        });
        return displayRow;
      }
    );
    
    $(document).ready(function() {
    
      // create an input field in each footer cell:
      $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
      } );
    
      var table = $('#example').DataTable({
        dom: 'lrtip' // hide the global filter box ('f')
      });
    
      // create change events to trigger a re-draw, which also calls the filter function:
      $('#example tfoot th input').keyup( function() {
        table.draw();
      } );
      $('#example td select').change( function() {
        table.draw();
      } );
        
    } );
    <html>
    <head>
      <meta charset="UTF-8">
      <title>Demo</title>
      <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
      <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
      <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
      <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
    
    </head>
    
    <body>
    
    <div style="margin: 20px;">
    
        <table id="example" class="display dataTable cell-border" style="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>
            <tbody>
                <tr>
                    <td>Tiger Nixon</td>
                    <td>System Architect</td>
                    <td>Edinburgh</td>
                    <td>61</td>
                    <td>2011/04/25</td>
                    <td>
                        <select>
                            <option >Adapter</option>
                            <option >Adapter1</option>
                            <option >Capacitor</option>
                            <option selected>Diode</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Garrett Winters</td>
                    <td>Accountant</td>
                    <td>Tokyo</td>
                    <td>63</td>
                    <td>2011/07/25</td>
                    <td>
                        <select>
                            <option >Adapter</option>
                            <option >Adapter1</option>
                            <option >Capacitor</option>
                            <option selected>Diode</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Ashton Cox</td>
                    <td>Junior "Technical" Author</td>
                    <td>San Francisco</td>
                    <td>66</td>
                    <td>2009/01/12</td>
                    <td>
                        <select>
                            <option >Adapter</option>
                            <option >Adapter1</option>
                            <option >Capacitor</option>
                            <option selected>Diode</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Cedric Kelly</td>
                    <td>Senior Javascript Developer</td>
                    <td>Edinburgh</td>
                    <td>22</td>
                    <td>2012/03/29</td>
                    <td>
                        <select>
                            <option >Adapter</option>
                            <option >Adapter1</option>
                            <option >Capacitor</option>
                            <option selected>Diode</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Airi Satou</td>
                    <td>Accountant</td>
                    <td>Tokyo</td>
                    <td>33</td>
                    <td>2008/11/28</td>
                    <td>
                        <select>
                            <option >Adapter</option>
                            <option >Adapter1</option>
                            <option >Capacitor</option>
                            <option selected>Diode</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Brielle Williamson</td>
                    <td>Integration Specialist</td>
                    <td>New York</td>
                    <td>61</td>
                    <td>2012/12/02</td>
                    <td>
                        <select>
                            <option >Adapter</option>
                            <option >Adapter1</option>
                            <option >Capacitor</option>
                            <option selected>Diode</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Herrod Chandler</td>
                    <td>Sales Assistant</td>
                    <td>San Francisco</td>
                    <td>59</td>
                    <td>2012/08/06</td>
                    <td>
                        <select>
                            <option >Adapter</option>
                            <option >Adapter1</option>
                            <option >Capacitor</option>
                            <option selected>Diode</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Rhona Davidson</td>
                    <td>Integration Specialist</td>
                    <td>Tokyo</td>
                    <td>55</td>
                    <td>2010/10/14</td>
                    <td>
                        <select>
                            <option >Adapter</option>
                            <option >Adapter1</option>
                            <option >Capacitor</option>
                            <option selected>Diode</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Colleen Hurst</td>
                    <td>Javascript Developer</td>
                    <td>San Francisco</td>
                    <td>39</td>
                    <td>2009/09/15</td>
                    <td>
                        <select>
                            <option >Adapter</option>
                            <option >Adapter1</option>
                            <option >Capacitor</option>
                            <option selected>Diode</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Sonya Frost</td>
                    <td>Software Engineer</td>
                    <td>Edinburgh</td>
                    <td>23</td>
                    <td>2008/12/13</td>
                    <td>
                        <select>
                            <option >Adapter</option>
                            <option >Adapter1</option>
                            <option selected >Capacitor</option>
                            <option>Diode</option>
                        </select>
                    </td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Age</th>
                    <th>Start date</th>
                    <th>Salary</th>
                </tr>
            </tfoot>
        </table>
    
    </div>
    
    
    
    </body>
    </html>

    Explanation

    I have added comments in the code to explain detailed steps, but overall, this works as follows:

    First, we remove the default searching function (this is used by the global search box) – and we also hide the global search box itself, using the DataTables dom option.

    We then define our replacement search function.

    This function needs to access the DOM, to extract all the selected values for each select list – which is what find(":selected").text() does.

    (We only need this for the final column in the table, so all the other columns can just use their cell contents without needing this extra step.)

    The search function is triggered every time we perform a draw(). When it fires, it is executed for each separate row in the table, and it determines whether each row should be displayed or hidden. It does this by returning a true or false value, based on comparing each field’s value against the column’s search term.

    If any search term fails to match the relevant field’s data, then that row is hidden. This is how we ensure all of the column filter instructions are evaluated in combination with each other. The solution uses the displayRow boolean to track the overall "displayable" status of each row.

    Finally, at the end of the script, we need to create event handlers which will force a DataTables re-draw, and which also cause our custom filter function to be invoked again. Note that we create these event handlers not only for the input fields in the footer, but also for each of the select lists – because a user can change a select list value, and filtering needs to immediately take such changes into account.

    Final Note

    With DataTables, there is often more than one way to accomplish a task. But in this case, I would definitely recommend using a custom function, for greatest flexibility.

    Login or Signup to reply.
  2. I found a solution as follows. I assigned the value entered in the textbox to a variable and read it from there.

    You still have to call the searc() function for the table search function to work.

     let customTable = $("#datatable").DataTable({
               dom: "'<'row''<'col-12'>><'row''<'col-xs-12 col-md-12 survey-export'><'col-md-6 col-xs-12 dt-buttons clearfix'B><'col-md-6 col-xs-12 dataTables_length'l>><'row'<'col-xs-12'f>r>t<'row'<'col-xs-12'p i>>",
              ajax: function (data, callback, settings) {
        var api = new $.fn.dataTable.Api(settings); // <--- create new api object using settings object
        var dataGroup = {
            currentPage: api.page() !== 0 ? api.page() : 1,
            size: api.page.len(),
            searchParam: api.search() !== '' ? api.search() : searchParam
        }
    
        $.ajax({
            type: 'GET',
            url: url,
            data: dataGroup,
            success: function (response) {
                if (response.isSuccess) {
                    var totalRecords = response.data.recordsTotal; // Toplam kayıt sayısı
                    var pageCount = response.data.recordsFiltered; // Toplam kayıt sayısı
                    var recordsPerPage = 50; // Sayfa başına gösterilecek maksimum kayıt sayısı
                    callback({
                        data: response.data.data,
                        recordsTotal: totalRecords,
                        recordsFiltered: totalRecords,
                    });
                    FuncyboxInit();
                }
            }
        });
    }
    });
    
      $('.survey-export').html('<input type="text" class="ant-input" placeholder="Ekipman Arama">');
    
      $(".survey-export input").on('keyup change', function (e) {
          debugger
          if (e.keyCode == 13 || this.value == "") {
              searchParam = this.value;
              customTable.search(this.value).draw();
          }
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search