如何通过使用下拉框更改数据表中的数据

时间:2019-01-27 10:17:00

标签: jquery datatables

我正在尝试通过使用下拉框更改数据表中显示的数据,用户可以在其中选择要查看的汽车的状态。我遇到的问题是数据没有更改下拉菜单中的状态已更改时。我正在使用django 1.8,请在下面查看我的代码。

jQuery /数据表

var datatable = $("#datatable").dataTable({
"fnServerData": function (sSource, aoData, fnCallback) {
 $('#DropDown_Select').change(function () {
   status = $(this).val()
   $.ajax({
       "type": "GET",
       "dataType": 'json',
       "contentType": "application/json; charset=utf-8",
       "url": sSource + "/" + status, //sending server side status and filtering table
       "data": aoData,
       "success": function (data) {

           fnCallback(data);
       }
   });

 });  
 }).columnFilter({
aoColumns: [
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
    { type: "text" },
]

});

数据表

<table id="datatable">
<thead>
    <th>Car</th>
    <th>Model</th>
    <th>Engine size</th>
    <th>Max speed</th>
    <th>Status</th>
</thead>
<tbody>
    <td>Example car</td>
    <td>Example make</td>
    <td>1.4</td>
    <td>110</td>
    <td>Status</td>
</tbody>
<tfoot>
    <th>Car</th>
    <th>Model</th>
    <th>Engine size</th>
    <th>Max speed</th>
    <th>Status</th>
</tfoot>

下拉框

<select id="DropDown_Select">
<option value="new">New</option>
<option value="old">Old</option>
</select> 

1 个答案:

答案 0 :(得分:0)

DataTables具有一个api,可用于过滤和操作表中显示的数据。我做了一些下拉过滤,功能看起来像这样:

table.api().columns(<select column>).search(val ? '^' + val + '$' : '', true, false).draw();

.draw();调用非常重要,因为任何时候您只要更改要由插件显示的数据,就需要告诉它重新绘制。

在创建下拉菜单时,我还发现使用api获取相关列中包含的所有选项来生成下拉菜单的选项很有用。该代码如下所示:

table.api().columns(<select column>).column.data().unique().sort().each(function (d, j) {
    select.append("<option value='" + d + "'>" + d + "</option>");
});