morne
morne

Reputation: 4179

DataTable custom search implementation

This might be a straight forward question, but I'm struggling to implement the solution I found. Lack of experience with JavaScript.

I'm trying to implement a custom search in a DataTables table, but the function I have only fires on startup and not on typing in the search box.

here is my original question.

and here is the solution for the search I'm trying.

$.fn.dataTable.ext.search.push(function( settings, data, dataIndex ) {
   var term = $('.dataTables_filter input').val().toLowerCase()
   for (var i=0, l=data.length; i<l; i++) {
     if ($(data[i], 'label').text().toLowerCase().indexOf(term) == 0 ) return true
   }
   return false
})

Ive tried it outside the $(document).ready(function(){, but it does not work.

here is the initialization of the DataTables table.

$(document).ready(function(){
.
.
.
    var oTable = $('#desktop_table').dataTable({
        "bInfo": false,
        "iDisplayLength": 15,
        "aLengthMenu": [15, 30, 50, 100],
        "sPaginationType": "full_numbers",
        "sDom": '<"top"i>frt<"bottom"lp><"clear">',
        "oLanguage": {
            "sLengthMenu": "Show _MENU_"
        },
        "sStripeOdd": "odd",
        "sStripeEven": "even",
        "rowReorder": true,
    });

}

Preview of a cell in my DataTables table

<td>
    <div class="plCell_desktop">
        <input type="radio" class="" data-lnk_id="414107671" data-group="RUTH">
        <label for="414107671">RUTH</label>
    </div>
</td>

Upvotes: 2

Views: 850

Answers (1)

Yojana Ambavkar
Yojana Ambavkar

Reputation: 106

$('input[type="radio"]').change(function () {
$.fn.dataTable.ext.search.push(function( settings, data, dataIndex ) {
   var term = $('.dataTables_filter input').val().toLowerCase()
   for (var i=0, l=data.length; i<l; i++) {
     if ($(data[i], 'label').text().toLowerCase().indexOf(term) == 0 ) 
      return true;
   }
   return false;
});
var table = $('#desktop_table').DataTable();
    table.draw();
});

Upvotes: 1

Related Questions