2017-04-23 75 views
0

DataTables在表格的右上方顯示一個搜索框,其正常工作狀態良好。下拉列表中選擇要搜索的字段

但我有一個requeriment,我需要在搜索框附近的下拉列表,用戶將選擇要搜索的字段。

舉例來說,有列FirstName,MiddleName和LastName。而不是搜索所有3列,用戶將在下拉列表中選擇(例如「MiddleName」),搜索將僅在該字段上進行。

其他問題是,這個DataTables是從服務器端通過ajax填充的,下拉菜單上的一些字段可以是「僅服務器」,即不會在DataTable上可見。然後,在我的例子中,設想顯示「FirstName」和「LastName」的DataTable,但允許搜索「MiddleName」。在這種情況下,我的服務器端代碼已準備就緒,我的問題只是關於如何設置DataTables:

  1. 有一些插件/選項爲此準備好了嗎?
  2. 要添加此下拉列表,我需要使用一些DataTable API創建和定位?
  3. 如何在請求到達服務器之前「攔截」搜索按鈕單擊,然後指定要搜索的正確列?

回答

1

這是您要求的第一部分。它將選擇框添加到數據表中。然後它將選定的值從選擇框中取出,並在ajax調用觸發器時將其添加到過濾器中。

演示在:http://live.datatables.net/zewiqiyo/1/edit

$(document).ready(function() { 
     var columns = [{ title: "Name" }, { title: "Position" }, { title: "Office" }, { title: "Age" }, { title: "Start_Date" }, { title: "Salary" }]; 

     // I use the preInt event to add the selectbox 
     // the css has a float right for the select box so it ends up next to the filter. 
     $("#example").one("preInit.dt", function() { 
      $sel = $("<select></select>"); 
      $sel.html("<option value='-1'>Select Column</option>"); 
      $.each(columns, function (i, opt) { 

       $sel.append("<option value='" + opt.title + "'>" + opt.title + "</option>"); 
      }); 
      $("#example_ddl").append($sel); 

     }); 
     var table = $('#example').DataTable(
      { 
       serverSide: true, 
       columns: columns, 
       // <"#example_ddl.filterddl"> added as a container for the selectbox 
       dom: '<"#example_ddl.filterddl">fti', 
       ajax: { 
        url: "examples/server_side/scripts/server_processing.php", 
        data: function (filter) { 

         // This is where you are intercepting what is being sent 
         // back to the server to add the column to search 

         var val = $("select", "#example_ddl").val(); 
         filter.search.searchColumn = val; 


        } 

       } 
      } 
     ); 
    }); 
+0

在我自己的工作,我竟增加了第二個標題行,放在一個文本框的每一個。當文本框不爲空時,我將它與該列中的搜索相關聯 – Bindrid

+0

在我目前的工作中,我沒有使用選擇框,而是將第二行添加到具有文本框的標題。如果用戶輸入了一個值然後回車,該列被搜索到該值。你可以在這裏看到一個例子http://live.datatables.net/mutafaqi/1/edit – Bindrid