【发布时间】:2021-09-30 21:28:37
【问题描述】:
我正在使用以下代码动态填充两个下拉菜单“searchProject”和“searchHR”。用户可以从“searchProject”中选择一个值,从“searchHR”中选择多个值来过滤数据表。
我正在尝试让第二个下拉菜单“searchHR”填充基于在第一个下拉菜单“searchProject”中选择的单个值的值。
这是我当前的代码:
var sortFunction = function (a, b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
};
$(document).ready(function () {
var ex_table = $('#data_table').DataTable({
"order": [],
pageLength: 50,
ajax: {
url: '/db',
dataSrc: "",
type: "POST",
'data': function (d) {
return $.extend({}, d, {
"project_name": $('#searchProject').val(),
"hour": $('#searchHR').val(),
});
},
"serverSide": true,
},
columns: [
{data: 'project_name'},
{data: 'id'},
{data: 'hour'},
],
"initComplete": function () {
ex_table.columns([0]).every(function () {
const column = this;
const select = $('#searchProject')
.on('change', function () {
const Project_val = $(this).val();
column.search(Project_val).draw();
});
column.data().unique().sort().each(function (d) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
ex_table.columns([2]).every(function () {
const column = this;
const select = $('#searchHR')
.on('change', function () {
var vals = $('option:selected', this).map(function (index, element) {
return $.fn.dataTable.util.escapeRegex($(element).val());
}).toArray().join('|');
column.search(vals.length > 0 ? '^(' + vals + ')$' : '', true, false).draw();
});
column.data().unique().sort(sortFunction).each(function (d) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
})
HTML:
<label for="searchProject"></label><select id="searchProject" class="js-example-basic-single" style="width: 10%">
<option></option>
</select>
<label for="searchHR"></label><select id="searchHR" class="js-example-basic-multiple" multiple="multiple" style="width:15%">
<option></option>
</select>
任何帮助将不胜感激。谢谢。
【问题讨论】:
标签: jquery datatables