← Go back

Combobox filters for Datatables


Posted on February 03, 2020 at 13:30 (GMT +00:00) by Colin

Today I'm going to show you how you can create combobox dropdown filters for Datatables. In my example I am using Bootstrap and JQuery as my base libraries.

So the idea is, when there are more than 1 column entry that is different, a combobox will display above the column, but below the actual header which includes the ordering event.



I am going to assume that you have experience using JQuery and jump straight in.

The first thing you need is your table.


<table class="table-responsive table table-striped table-hover">
	<thead>
		<tr><th scope="col">#</th><th scope="col">m2</th><th scope="col">Floor</th><th scope="col">Type</th><th scope="col">Price</th><th scope="col" style="text-align:right;">~ Plan</th></tr>
		<tr><th scope="col"></th><th scope="col"></th><th scope="col"></th><th scope="col"></th><th scope="col"></th><th scope="col" style="text-align:right;"></th></tr>
	</thead>

	<tbody>
		<!-- table rows here -->
	</tbody>

	<tfoot><th scope="col">#</th><th scope="col">m2</th><th scope="col">Floor</th><th scope="col">Type</th><th scope="col">Price</th><th scope="col" style="text-align:right;">~ Plan</th></tr><tfoot>
</table>


Next up, on your Datatable initialisation, you'll need the option orderCellsTop as true followed by an initComplete function that will perform the thead update.


initComplete: function () {			
	this.api().columns().every( function (index) {
		var _uq = this. cache('search').sort().unique();
		if (_uq.count() > 1) {
			var _t = this;
						
			var select = $('<select><option value=""></option></select>') .appendTo( $('#aptable thead tr:eq(1) th:eq('+index+')') )
				.on( 'change', function () { _t .search( $(this).val() ).draw(); } );						
					 
			_uq.each( function ( d ) { select.append( $('<option value="'+d+'">'+d+'</option>') );	});
		}						
	} );
},


If you would like to hide the original filter box you can call


$('.dataTables_filter').hide();	


Your whole initalization script should look something like this:


<script>
$(document).ready(function () {

	$('#aptable').DataTable({
		initComplete: function () {			
			this.api().columns().every( function (index) {
				var _uq = this. cache('search').sort().unique();
				if (_uq.count() > 1) {
					var _t = this;
						
					var select = $('<select><option value=""></option></select>') .appendTo( $('#aptable thead tr:eq(1) th:eq('+index+')') )
						.on( 'change', function () { _t .search( $(this).val() ).draw(); } );						
					 
					_uq.each( function ( d ) { select.append( $('<option value="'+d+'">'+d+'</option>') );	});
				}						
			} );
		},
	
		orderCellsTop: true,
		responsive: true,
		paging: false		
	});

	$('.dataTables_filter').hide();	
});
</script>	


If you find this useful or If you require an explanation of the code, just drop me a comment and I'll get back to you.

/signing off
/Programming