Datatables exact word search

前端 未结 3 1949
天命终不由人
天命终不由人 2020-12-11 23:32

Hi I\'m using datatables and I would like to filter my data by an exact word.

My table data looks like below;

+-----+----------+
| num | status   |
+         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 00:22

    If think you are better off with a custom filter for this task. unbind the default handlers and perform a exact match filter each time instead. If you have a table

    var table = $('#example').DataTable()  
    

    Then use a exact match custom filter this way

    $('.dataTables_filter input').unbind().bind('keyup', function() {
       var searchTerm = this.value.toLowerCase()
       if (!searchTerm) {
          table.draw()
          return
       }
       $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
          for (var i=0;i

    here is a demo -> http://jsfiddle.net/hmjnqjbs/1/ try search for tokyo.


    OK. I realize the question not is about "exact words" as in exact match filter, but more a whole word search. We want to see Vaio Q900 when we search on vaio, but we do not want to see VaioQ900 because Vaio here not is a whole word. This problem is simply solved by using a regex word boundary \b :

    $('.dataTables_filter input').unbind().bind('keyup', function() {
       var searchTerm = this.value.toLowerCase(),
           regex = '\\b' + searchTerm + '\\b';
       table.rows().search(regex, true, false).draw();
    })
    

    OP's fiddle from the comment below updated -> http://jsfiddle.net/hmjnqjbs/3/

    Now active, vaio and so on works as expected.

提交回复
热议问题