首页 > 解决方案 > 按列过滤数据表以获取范围内的结果(单击按钮)

问题描述

我的 html 文档中有一个包含 9 列的数据表,该数据表已创建并与过滤和搜索完美配合。该表是使用以下代码创建的:

var productPricingTable = $('#productPriceOpportunitiesTable').DataTable({
      dom: '',       
      "paging": false,
      "info": false
});

我有一个按钮,我正在尝试制作它,以便在按下按钮时,它将过滤数据表,以便只有第 9 列值在 1.00 - 1.50 之间的行。

我在下面的函数中正确检测到我的按钮按下,但我正在努力编写将正确过滤数据表的代码。

$("#productTableToggleCheckbox").on('change', function() {
  //productTableToggleCheckbox
  if ($(this).is(':checked')) {
      switchStatus = $(this).is(':checked');
      //when switch is turned on, filter datatable to only show results where the 9th column's value is between 1.00 to 1.50
      //filter table
      //productPricingTable.column( 8 ).search( $(1.07).text() );
      //productPricingTable.draw()
  }
  else {
      switchStatus = $(this).is(':checked');
      //switch is turned off
  }
});

我目前正在尝试,productPricingTable.column( 8 ).search( $(1.07).text() );但似乎没有任何事情发生。有没有办法修改这行代码,以便正确过滤表格?就像是:

productPricingTable.column( 8 ).search( col8.value( x >= 1.00 && x <= 1.50) );

标签: javascriptjqueryhtmldatatable

解决方案


回答:

    $.fn.dataTable.ext.search.push(
      function( settings, data, dataIndex ) {
        //if 'Show Only Price Opportunities' button is toggled on:
        if($("#productTableToggleCheckbox").is(':checked')){
          var CPI = parseFloat( data[8] ) || 0; // use data for the age column
          console.log("CPI = ", CPI)
          if(CPI < 0.90 || CPI > 1.10){
            //include row in table if CPI matches criteria
            return true;
          }else{
            //if CPI does not match criteria; 
            return false;
          }

        }else{
          return true;
        }
      }
  );


推荐阅读