Reputation: 899
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.
Upvotes: 1
Views: 1491
Reputation: 153
you can modified like this
column.data().unique().sort().each(function (d, j) {
d&&d.length&&select.append('<option value="' + d + '">' + d + '</option>')
});
I found one row lose its value as below:
Upvotes: 1
Reputation: 773
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>')
}
});
Upvotes: 1
Reputation: 26
You could set the value of "Show All" like below.
<select><option value="Show All">Show all</option><option value=""></option><option value="Free Biscuits">Free Biscuits</option><option value="Free PS4">Free PS4</option><option value="Free TV">Free TV</option><option value="Free XBOX">Free XBOX</option></select>
And once the page load is complete, you could use JQuery to remove the empty drop down option. The below option remove the dropdown item based on index
$('.dropdown-filter-div option:eq(1)').remove()
or use the below JQuery, the below code removes the dropdown item based on value (which is empty in your code)
$('.dropdown-filter-div option[value=""]').remove()
Hope this helps.
Upvotes: 0