ColReorder with Select2 multi select issue.
ColReorder with Select2 multi select issue.
nglenn
Posts: 1Questions: 1Answers: 0
I have a C# MVC app with datatables and Select2 multi select working perfectly.
I added colReorder: true; and it allows me to reorder the columns and the Select2 multi select dropdown list moves with it but the filter doesn't seem to filter on the correct column.
Any help is much appreciated
$('.dtTable').DataTable({
fixedHeader: { header: true, footer: true },
paging: false,
colReorder: true,
columnDefs: [
{ targets: [-1], orderable: false, searchable: false }
],
dom: "<'row'<'col-auto'B><'col-auto'f>>" + "<'row'<'col-sm-12'tr>>" + "<'row'<'col-sm-12'i>>",
buttons: [{ extend: 'collection', text: 'Export', className: "btn-sm", buttons: ['copy', 'excel', 'pdf', 'print'] }],
initComplete: function () {
count = 0;
this.api().columns('.dtFilterable').every(function (i) {
var title = this.header();
//replace spaces with dashes
title = $(title).html().replace(/[\W]/g, '');
var column = this;
var select = $('<select id="' + title + '" class="form-control form-control-sm select2" ></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
//Get the "text" property from each selected data
//regex escape the value and store in array
var data = $.map($(this).select2('data'),
function (value, key) {
return value.text ? '^' + $.fn.dataTable.util.escapeRegex(value.text) + '$' : null;
});
//if no data selected use ""
if (data.length === 0) {
data = [""];
}
//join array into string with regex or (|)
var val = data.join('|');
//search for the option(s) selected
column
.search(val ? val : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>');
});
//use column title as selector and placeholder
$('#' + title).select2({
multiple: true,
closeOnSelect: true,
placeholder: "- All -",
allowClear: true
});
//initially clear select otherwise first option is selected
$('.select2').val(null).trigger('change');
});
}
});
Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.
This discussion has been closed.
Answers
The problem is the closure on the
column
variable. it retains the index to the original column index, so you need to transpose the index usingcolReorder.transpose()
.Allan