问题
I'm trying to search my table on multiple columns at the same time. Example
----------------------------
| Col1 | Col2 | Col3 |
----------------------------
| abcd | efgh | 12 |
| bcde | efgh | 34 |
| cdef | efgh | 56 |
----------------------------
I want to search "cd" in Col1 and "34" in Col3, so that the result would be
----------------------------
| Col1 | Col2 | Col3 |
----------------------------
| bcde | efgh | 34 |
----------------------------
I've added some input fields in my table's thead
and when my custom event is triggered, Here is what I came up with:
$('#datatable_ajax thead').on( 'doneTyping', '.search-on-type', function(e){
if ( $(this).val() ) {
var colX = [];
var values = [];
$('#datatable_ajax thead .search-on-type').each(function(){
if($(this).val() == "")
return;
var visIdx = $(this).closest('th').index();
var idx = dTable.column.index( 'fromVisible', visIdx );
colX.push(idx);
values.push($(this).val());
});
if( colX.length == 3){
dTable.clearPipeline().columns( colX[0] ).search( values[0] ).columns( colX[1] ).search( values[1] ).columns( colX[2] ).search( values[2] ).draw();
} else if ( colX.length == 2){
dTable.clearPipeline().columns( colX[0] ).search( values[0] ).columns( colX[1] ).search( values[1] ).draw();
} else {
dTable.clearPipeline().columns( colX[0] ).search( values[0] ).draw();
}
}
});
this code is working as expected.
But as you can see, the if-elseif-else is quite a bad solution, since I could have more than 3 fields which I want to search together, but I don't want to manually add an elseif
each time I add a new searchable column.
I tried to find a better solution but I only found solutions for searching multiple columns with the same value, which is not what I need.
I noticed that .columns()
accept an array as arguments, but .search()
doesn't.. ( or at least, it does accept arrays, but they are transformed into comma separated string, which will be searched on the selected columns)
Is there any workaround for this?
回答1:
One thing you could do, is fill up your values
array with a regex pattern like (.*?)
(that matches anything) for all columns for which no search filter has been defined.
This would allow you to reduce your if-elseif-else to a single statement :
$('#datatable_ajax thead').on( 'doneTyping', '.search-on-type', function(e) {
if ($(this).val()) {
var colX = [], values = [], filter;
$('#datatable_ajax thead .search-on-type').each(function() {
filter = $(this).val();
if(filter == "") {
values.push("(.*?)"); // Regex that matches anything
} else {
values.push(filter);
}
colX.push(dTable.column.index( 'fromVisible', $(this).closest('th').index() ));
});
dTable.clearPipeline().columns( colX[0] ).search( values[0], true, false )
.columns( colX[1] ).search( values[1], true, false )
.columns( colX[2] ).search( values[2], true, false )
.draw();
}
});
来源:https://stackoverflow.com/questions/43114045/datatables-search-on-multiple-columns