Reputation: 506
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.
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
So how could I achieve a search inside the td, maybe with regex, finding those selected option ?
Upvotes: 2
Views: 6559
Reputation: 58930
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 ...
});
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.
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();
});
See updated example for code and demonstration.
Upvotes: 4