我在html页面上有数据表.在我的Datatable中,我在页脚处进行了按列搜索.此搜索适用于所有列,但有一列包含 Select 选项元素(下拉列表),因此不适用.每次它开始搜索而不是列表的选定值时,它都在搜索所有列表值.

This my table looks like :- enter image description here

here you can see position search is working fine. its draw match value correctly. enter image description here

薪资列的列表值包含:-适配器、适配器1、 capacitor 、二极管

enter image description here

But when i type any value which is not present in list then it show correctly, So search is working but it takes all value instead of selected value :- enter image description here

你能帮我一下吗.

下面是我的代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BootStrap</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> -->

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-table.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.3.4/css/select.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://editor.datatables.net/extensions/Editor/css/editor.dataTables.min.css">

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/datetime/1.1.2/css/dataTables.dateTime.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css">
<!-- <link type="text/css" href="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/css/dataTables.checkboxes.css" rel="stylesheet" /> -->
<!-- https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css -->
</head>
<body>

<div class="container mb-3 mt-3">

<div class="panel panel-default">
  <div class="panel-heading"><b> Demo </b> </div>

  <div class="panel-body">
    
    <div class="tbl_user_data"><table class="table table-striped table-bordered" id = "mydatatable"
>

<thead>
           <tr>
           <th></th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
</thead>
<tbody>
            <tr row_id = "123">
            <td></td>
                <td><div class="row_data" edit_type="click" col_name="fname">Tiger Nixon</div></td>
                <td><div class="row_data" edit_type="click" col_name="pos">Developer</div></td>
                <td><div class="row_data" edit_type="click" col_name="off">Edinburgh</div></td>
                <td><div class="row_data" edit_type="click" col_name="age">61</div></td>
                <td><div class="row_data" edit_type="click" col_name="startdate">2011/04/25</div></td>
                <td><div class="row_data" edit_type="lov" col_name="sal">
                <select class="example-dropUp" id="selhw">
                <option >Adapter</option>
                <option selected>Adapter1</option>
                <option >Capacitor</option>
                 <option >Diode</option>
                </select>
                </div></td>
            </tr>
                        <tr row_id = "124">
            <td></td>
                <td><div class="row_data" edit_type="click" col_name="fname">Tiger Nixon1</div></td>
                <td><div class="row_data" edit_type="click" col_name="pos">System Architect1</div></td>
                <td><div class="row_data" edit_type="click" col_name="off">Edinburgh1</div></td>
                <td><div class="row_data" edit_type="click" col_name="age">611</div></td>
                <td><div class="row_data" edit_type="click" col_name="startdate">2011/04/25</div></td>
                <td><div class="row_data" edit_type="lov" col_name="sal">
                <select class="example-dropUp" id="selhw">
                <option >Adapter</option>
                <option >Adapter1</option>
                <option selected>Capacitor</option>
                 <option >Diode</option>
                </select>
                </div></td>
            </tr>
                        <tr row_id = "125">
            <td></td>
                <td><div class="row_data" edit_type="click" col_name="fname">Tiger Nixon2</div></td>
                <td><div class="row_data" edit_type="click" col_name="pos">System Architect2</div></td>
                <td><div class="row_data" edit_type="click" col_name="off">Edinburgh2</div></td>
                <td><div class="row_data" edit_type="click" col_name="age">61</div></td>
                <td><div class="row_data" edit_type="click" col_name="startdate">2011/04/25</div></td>
                <td><div class="row_data" edit_type="lov" col_name="sal">
                <select class="example-dropUp" id="selhw">
                <option >Adapter</option>
                <option >Adapter1</option>
                <option >Capacitor</option>
                 <option selected>Diode</option>
                </select>
                </div></td>
                               <tfoot>
            <tr>
            <th></th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
        </tbody>
</table>
  </div>
</div>
</div>

 

<div class="panel panel-default">
  <div class="panel-heading"><b>HTML Table Edits/Upates</b> </div>

  <div class="panel-body">
    
    <p>All the changes will be displayed below</p>
    <div class="post_msg"> </div>

  </div>

 
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/esm/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/select/1.3.4/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="/js/bootstrap-table.min.js"></script>
<script src="https://editor.datatables.net/extensions/Editor/js/dataTables.editor.min.js"></script>
<script src="https://cdn.datatables.net/datetime/1.1.2/js/dataTables.dateTime.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>





<!-- <script type="text/javascript" src="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/js/dataTables.checkboxes.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function($)
{

     $('#mydatatable tfoot th').each( function (index) {
            //alert("in Tfoot");
            console.log("tfoot th");
             var title = $(this).text();
             var notapplyFilteronColumn =[0]
             if(notapplyFilteronColumn.indexOf(index) < 0 )
                {
                         $(this).html( '<input type="text" id="txtName'+index+'" placeholder="Search '+title+'" data-index="'+index+'" />' );
                }
         } );

 var table = $('#mydatatable').DataTable({
        order:[[3,'desc']],
//      processing: true,
        pagingType:'full_numbers',
         pageLength:20,
         scrollY:500,
         scrollX:true,
         searchable: true,
        // bFilter: false,
        lengthMenu:[[5,10,25,50,-1],[5,10,25,50,"All"]],    
         select: {
             style: 'multi'
         },
         columnDefs: [ {
             orderable: false,
             className: 'select-checkbox',
             targets:   0,
         }
         ],

         select: {
             style:    'multi',
             selector: 'td:first-child'
         },
         search:
             {
             caseInsensitive: true,
             smart: true
             },
         order: [[ 1, 'asc' ]],
        
         initComplete: function () {
             // Apply the search
       console.log("Inside initcomplete");
                this.api().columns().every( function (index) {          
                  var that = this;  
                 $( 'input', this.footer() ).on( 'keyup change clear', function () {
                     console.log("inside Keyup change");
                     console.log("index = "+index);
                if ( that.search() !== this.value ) {
                         that
                             .search(this.value)
                             .draw();
                     }  
                
                 } );    
                 
             } );
                

         }   //initcomplete


         
     }); //dt

    

}); 

</script>


</body>
</html>

推荐答案

以这种方式使用search(...) API调用时,只能搜索每列中的所有内容.在您的 case 中,这有两个问题:

(1) 包含select列表的每个单元格实际上都包含<select>...</select>元素的完整HTML文本,包括select所使用的所有选项.这就是为什么搜索似乎不起作用.事实上,它工作正常.无论是selected选项,它都会找到每个 Select 选项.

(2) 用户可以在任何时候 Select 任何 Select 选项,而所有此类更改只在DOM中捕获.底层DataTable(即JavaScript对象)对此类更改一无所知.因此,没有直接的方法告诉DataTables search()函数这些更改.

Solution

一种解决方案是使用$.fn.dataTable.ext.search创建自定义DataTables搜索函数.你可以看到a basic example here个.

下面是一个基于您问题中代码的简化版本的可运行代码段,展示了如何调整$.fn.dataTable.ext.search以同时处理包含 Select 列表的列:

// remove the default global filter function:
while($.fn.dataTable.ext.search.length > 0) {
  $.fn.dataTable.ext.search.pop();
}

// add our custom filter function:
$.fn.dataTable.ext.search.push(
  function( settings, data, rowIdx ) {
    // get the TD node containing the drop-down list:
    var selectListTdNode = $('#example').DataTable().rows(rowIdx).nodes().to$().find( 'td' )[5]
    // get the selected value:
    var selection = $( selectListTdNode ).find(":selected").text();
    
    // process each field in the row:
    var displayRow = true; // start by assuming the row should be displayed
    data.forEach(function (item, idx) {
      // for the 6th column (idx = 5), we need to use the selected drop-down
      //  value, and not the contents of the cell:
      item = (idx === 5) ? selection : item;
      
      var searchField = $('#example').DataTable().columns(idx).footer();
      var searchValue = $(searchField).find( 'input' ).val();
      // should the row be displayed? 'false' means 'do not display':
      if (searchValue !== '' & !item.toLowerCase().includes(searchValue.toLowerCase())) {
        displayRow = false;
      }
    });
    return displayRow;
  }
);

$(document).ready(function() {

  // create an input field in each footer cell:
  $('#example tfoot th').each( function () {
    var title = $(this).text();
    $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
  } );

  var table = $('#example').DataTable({
    dom: 'lrtip' // hide the global filter box ('f')
  });

  // create change events to trigger a re-draw, which also calls the filter function:
  $('#example tfoot th input').keyup( function() {
    table.draw();
  } );
  $('#example td select').change( function() {
    table.draw();
  } );
    
} );
<html>
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
  <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">

</head>

<body>

<div style="margin: 20px;">

    <table id="example" class="display dataTable cell-border" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>
                    <select>
                        <option >Adapter</option>
                        <option >Adapter1</option>
                        <option >Capacitor</option>
                        <option selected>Diode</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011/07/25</td>
                <td>
                    <select>
                        <option >Adapter</option>
                        <option >Adapter1</option>
                        <option >Capacitor</option>
                        <option selected>Diode</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Ashton Cox</td>
                <td>Junior "Technical" Author</td>
                <td>San Francisco</td>
                <td>66</td>
                <td>2009/01/12</td>
                <td>
                    <select>
                        <option >Adapter</option>
                        <option >Adapter1</option>
                        <option >Capacitor</option>
                        <option selected>Diode</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2012/03/29</td>
                <td>
                    <select>
                        <option >Adapter</option>
                        <option >Adapter1</option>
                        <option >Capacitor</option>
                        <option selected>Diode</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>33</td>
                <td>2008/11/28</td>
                <td>
                    <select>
                        <option >Adapter</option>
                        <option >Adapter1</option>
                        <option >Capacitor</option>
                        <option selected>Diode</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Brielle Williamson</td>
                <td>Integration Specialist</td>
                <td>New York</td>
                <td>61</td>
                <td>2012/12/02</td>
                <td>
                    <select>
                        <option >Adapter</option>
                        <option >Adapter1</option>
                        <option >Capacitor</option>
                        <option selected>Diode</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Herrod Chandler</td>
                <td>Sales Assistant</td>
                <td>San Francisco</td>
                <td>59</td>
                <td>2012/08/06</td>
                <td>
                    <select>
                        <option >Adapter</option>
                        <option >Adapter1</option>
                        <option >Capacitor</option>
                        <option selected>Diode</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Rhona Davidson</td>
                <td>Integration Specialist</td>
                <td>Tokyo</td>
                <td>55</td>
                <td>2010/10/14</td>
                <td>
                    <select>
                        <option >Adapter</option>
                        <option >Adapter1</option>
                        <option >Capacitor</option>
                        <option selected>Diode</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Colleen Hurst</td>
                <td>Javascript Developer</td>
                <td>San Francisco</td>
                <td>39</td>
                <td>2009/09/15</td>
                <td>
                    <select>
                        <option >Adapter</option>
                        <option >Adapter1</option>
                        <option >Capacitor</option>
                        <option selected>Diode</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Sonya Frost</td>
                <td>Software Engineer</td>
                <td>Edinburgh</td>
                <td>23</td>
                <td>2008/12/13</td>
                <td>
                    <select>
                        <option >Adapter</option>
                        <option >Adapter1</option>
                        <option selected >Capacitor</option>
                        <option>Diode</option>
                    </select>
                </td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>

</div>



</body>
</html>

Explanation

我在代码中添加了注释来解释详细的步骤,但总的来说,它的工作原理如下:

首先,我们删除了默认的搜索功能(这是由全局搜索框使用的),我们还使用DataTables dom选项隐藏了全局搜索框本身.

然后定义替换搜索函数.

这个函数需要访问DOM, for each Select 列表提取所有 Select 的值——find(":selected").text()就是这么做的.

(我们只需要在表中的最后一列使用这个,所以所有其他列都可以使用它们的单元格内容,而不需要这个额外的步骤.)

搜索功能会在每次执行draw()次搜索时触发.当它触发时,它将针对表中的每一行执行,并确定是否应显示或隐藏每一行.它通过将每个字段的值与列的搜索项进行比较,返回truefalse值来实现这一点.

如果any搜索词与相关字段的数据不匹配,则该行被隐藏.这就是我们如何确保所有列筛选器指令都是相互结合判断的.该解决方案使用displayRow布尔值来跟踪每行的整体"可显示"状态.

最后,在脚本结束时,我们需要创建事件处理程序,它将强制重新绘制DataTables,并且还会导致再次调用自定义筛选函数.请注意,我们不仅为页脚中的输入字段创建了这些事件处理程序,还 for each Select 列表创建了这些事件处理程序——因为用户可以更改 Select 列表的值,过滤需要立即考虑这些更改.

Final Note

对于数据表,通常有多种方法来完成任务.但在这种情况下,为了获得最大的灵活性,我绝对建议使用自定义函数.

Javascript相关问答推荐

如何循环访问对象数组并以关键值形式获得结果?

reaction useEffect KeyDown for each 条目配音输出

如何访问Json返回的ASP.NET Core 6中的导航图像属性

如何在使用fast-xml-parser构建ML时包括属性值?

判断表格单元格中是否存在文本框

如何在不创建新键的情况下动态更改 map 中的项目?

在这种情况下,如何 for each 元素添加id?

Angular material 拖放堆叠的牌副,悬停时自动展开&

如何从Intl.DateTimeFormat中仅获取时区名称?

用于编辑CSS样式的Java脚本

如何在Vue 3中创建自定义 Select 组件,并将选项作为HTML而不是props 传递?

将核心模块导入另一个组件模块时存在多个主题

Eval vs函数()返回语义

如何在FastAPI中为通过file:/URL加载的本地HTML文件启用CORS?

在查看网页时,如何使HTML中的按钮工作方式类似于鼠标上的滚轮或箭头键?

如何使用抽屉屏幕及其子屏幕/组件的上下文?

如何在AG-Grid文本字段中创建占位符

如何在移动设备中使用JAVASSCRIPT移除点击时的焦点/悬停状态

如何阻止外部脚本进入顶层导航

如果查询为空,则MongoDB将所有文档与$in匹配