Scott Scott - 6 months ago 75
jQuery Question

Datatables - jQuery/Javascript dropdown box contains empty selector

I have made a dropdown filter for my datatable, as you can see in the jsfiddle (https://jsfiddle.net/6k0bshb6/45/) there is an option which contains no data - if you look through inspect element

<option value=""></option>
how can I remove this empty container and tell my datatable function for dropdown boxes to skip appending options to the select option when they are empty.

// Dropdown filter function for dataTable from hidden column number 5 for filtering gifts.
initComplete: function () {
this.api().columns(5).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#contracts_control-panel").find("div").eq(1)) // append dropdown to div 2 in control panel
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val());
column.search(val ? '^' + val + '$' : '', true, false)
.draw();
dataTable.page.len(5).draw(); //reset pagination after dropdown filter change.
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});


I tried wrapping an if statement around the append like this...

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


but it didn't work for some reason.

Answer

Use d !== "" instead of d !== undefined. See fiddle.

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