JQuery数据表对列内的选择进行排序 [英] JQuery Datatables sorting a select inside a column
问题描述
我正在使用DataTables 1.10.12和JQuery 1.12.3
I am using DataTables 1.10.12 and JQuery 1.12.3
我在排序包含下拉列表的列时遇到了问题
I got a problem with sorting a column that have dropdown list inside it
我正在使用多选过滤器.
I am using the multi select filter.
一切正常,可能是因为multi_select中option标记的值导致我无法对包括select(具有selected ="selected"选项)的列进行排序,我不知道如何填充
All is working fine, prob is that it can't sort the column including the select (that has selected="selected" option) probably because of the value of the option tag in the multi_select that I don't know how to fill
那么我如何才能在td内实现搜索(也许使用正则表达式),找到那些选定的选项?
So how could I achieve a search inside the td, maybe with regex, finding those selected option ?
推荐答案
解决方案
您可以使用 columnDefs
使用基于零的索引来定位特定列 targets
选项和
SOLUTION
You can use columnDefs
to target a specific column using zero-based index in targets
option and render
to return selected value during searching (type === 'filter'
) or sorting (type === 'order'
).
var table = $('#example').DataTable({
columnDefs: [
{
targets: [0,1,2,3],
render: function(data, type, full, meta){
if(type === 'filter' || type === 'sort'){
var api = new $.fn.dataTable.Api(meta.settings);
var td = api.cell({row: meta.row, column: meta.col}).node();
data = $('select, input', td).val();
}
return data;
}
}
],
// ... skipped ...
});
上面的代码使用option
元素的值来确定要排序/搜索的值.但是,在更新的示例中,您使用数字ID作为值.
The code above uses values of option
elements to determine value to sort/search. However in your updated example, you're using numeric IDs as values.
要改为使用option
的文本,请使用下面显示的修改后的代码:
To use text of option
instead, use modified code shown below:
var table = $('#example').DataTable({
columnDefs: [
{
targets: [0,1,2,3],
render: function(data, type, full, meta){
if(type === 'filter' || type === 'sort'){
var api = new $.fn.dataTable.Api(meta.settings);
var td = api.cell({row: meta.row, column: meta.col}).node();
var $input = $('select, input', td);
if($input.length && $input.is('select')){
data = $('option:selected', $input).text();
} else {
data = $input.val();
}
}
return data;
}
}
],
// ... skipped ...
});
一旦数据如下所示发生变化,您还需要使单元格数据无效(根据此解决方案).
Also you need to invalidate cell data once data changes as shown below (according to this solution).
$('tbody select, tbody input', table.table().node()).on('change', function(){
table.row($(this).closest('tr')).invalidate();
});
演示
有关代码和演示,请参见更新的示例.
这篇关于JQuery数据表对列内的选择进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!