Beginner Beginner - 1 month ago 5
Javascript Question

Column filtering of selected columns

In my project I am using jQuery DataTables. Id like to sort just 1 (or 2) of the columns. There is a datatables example that adds a

select
menu to each columns footer. I was able to use my extremely limited JavaScript skills to move the dropdowns to a div above the table but I am lost at how to have the menus appear for only select few columns i.e. how to have a
select
menus for ONLY the
position
column (or may be name and position) . My code ( CODEPEN ):

Javascript:

$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $("#sort") )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);

column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );

column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
} );
} );

Answer

Change

this.api().columns().every( function () {

to

this.api().columns([0, 1]).every( function () {

where 0 and 1 are zero-based column indexes for which you want the filter to appear.

See updated codepen for code and demonstration.