使用jQuery DataTables在表中的选择框中搜索

时间:2015-09-04 04:31:03

标签: javascript jquery datatables

我有一个清单表:

<select name="time">
   <option value="">Select time</option>
   <option value="AM">AM</option>
   <option value="PM">PM</option>
</select>
<table id="delivery">
   <thead>
      <tr>
         <th>ID</th>
         <th>Name</th>
         <th>Time</th>
     </tr>
   </thead>
   <tbody>
      <tr>
         <td>1</td>
         <td>A</td>
        <td>AM</td>
      </tr>
      <tr>
         <td>2</td>
         <td>B</td>
         <td>PM</td>
      </tr>
      <tr>
         <td>3</td>
         <td>C</td>
         <td>AM</td>
      </tr>
   </tbody>
</table>

我的剧本:

$.fn.dataTableExt.afnFiltering.push(
   function( oSettings, aData, iDataIndex ) {
      //filter on current position which is column 3            
      colFilterID = 3;

      //get our filter element
      filterElement = aData[colFilterID] * 1;

      //get our filter time from the SELECT drop down in header of column
      filterTime = $("select[name='time']").val();

      if(filterTime == '') {
         return true;
      }

      if(filterTime == filterElement ) {
         return true;
      }
});
$("select[name='time']").on('change', function() {
   oTable.fnDraw();
});

var table = $('#delivery');
var oTable = table.dataTable();

我无法使用AMPM值按第三列过滤记录。

1 个答案:

答案 0 :(得分:0)

  

<强>原因

您的代码存在几个问题:

  • 列索引从零开始,因此第三列的索引为2
  • 您尝试将字符串转换为数字aData[colFilterID] * 1,将字符串转换为NaN
  • 您的代码并不总是返回值,如果字符串不匹配,则需要返回false
  

<强>解

$.fn.dataTableExt.afnFiltering.push(
   function( oSettings, aData, iDataIndex ) {
      //filter on current position which is column 3 (zero-based index is 2)
      colFilterID = 2;

      //get our filter element
      filterElement = aData[colFilterID];

      //get our filter time from the SELECT drop down in header of column
      filterTime = $("select[name='time']").val();

      if(filterTime == '') {
         return true;
      }

      if(filterTime == filterElement) {
         return true;
      } else {
         return false;    
      }
});
  

<强>样本

请参阅this jsFiddle以获取代码和演示。