首页 > 解决方案 > 数据表搜索 td 属性

问题描述

我一直在搜索表格上的数据搜索属性时遇到问题。

这就是我通过 Datatable() 添加属性的方式:

createdRow: function( row, data, dataIndex ) {
  //Check if merchant has psp and add it to the cell
  if(data.parent_id) {
    $( row ).find('td:eq(0)').attr('data-search', 'merchant');
  } else {
    $( row ).find('td:eq(0)').attr('data-search', 'psp');
  }
}

我想使用下拉菜单根据属性值进行搜索,我尝试这样做:

 $('#dropdown1').on('change', function() {
       if(this.value === ' ') {
          table
          .columns( 0 )
          .search( '' )
          .draw();
        } else {
          table
          .columns( 0 )
          .search( this.value )
          .draw();
        }

 })

但这似乎不起作用。

请在此处找到带有模拟数据的小提琴https://jsfiddle.net/designtocode/mdfeL7tp/14/

任何帮助或帮助将不胜感激。

标签: javascriptjqueryajaxlaraveldatatables

解决方案


您可以使用搜索插件并直接检查是否parent_id根据下拉列表中选择的值设置了行的 。

这将是搜索插件:

$.fn.dataTable.ext.search.push(function (settings, searchData, index, rowData, counter) {
  let shouldDisplay = true;
  let searchValue = $('#dropdown1').val();
  if (searchValue == 'merchant') {
    shouldDisplay = rowData.parent_id ? true : false;
  } else if (searchValue == 'psp') {
    shouldDisplay = rowData.parent_id ? false : true;
  }
  return shouldDisplay;
});

如果它发生变化,您的下拉列表只需在桌子上调用一个平局:

$('#dropdown1').on('change', function() {
  table.draw();
});

推荐阅读