Reputation: 2247
i have created a custom select field into my datatable
html = '<div class="col-md-3"><select id="filterleads" class="filterleads form-control">';
html += '<option value="all">All Leads</option>';
html += '<option value="processed">Processed Leads</option>';
html += '<option value="unprocessed">Unprocessed Leads</option>';
html += '</select></div>';
$("div.toolbar").html(html);
now when the select changes i want it to send its value with the datatable ajax so i can filter records according to that
this is how im doing this
var table = $('#allleadstable').DataTable( {
"processing": true,
"serverSide": true,
"responsive": true,
"iDisplayLength": 50,
"sScrollX": "100%",
"order": [[ 1, "desc" ]],
"sScrollXInner": "100%",
"bScrollCollapse": true,
"ajax": {
url:"/leads",
data: {
"leadfilter": ($("#filterleads").val() ? $("#filterleads").val() : 'all')
}
},
"scrollX":true,
"scrollCollapse": true,
//"sDom": '<"top"flip>rt<"bottom"flip><"clear">',
"dom": '<"toolbar">frtip',
columnDefs: [
{ width: 60, targets: 0 },
{ width: 50, targets: 1 },
{ width: 50, targets: 2 },
{ width: 150, targets: 3 },
{ width: 150, targets: 4 },
{ width: 100, targets: 5 },
//{ width: 100, targets: 7 },
{ width: 100, targets: 6 }
]
});
$(document).on("change", "#filterleads", function(event) {
table.ajax.reload();
});
The problem is that it doesn't find $("#filterleads")
and always send the value 'all' even when i change the select
How do I send its value everytime I change select?
Upvotes: 1
Views: 393
Reputation: 469
For one dynamic field and 2 static its also may looks like:
ajax: {
url: '/action.php',
data: {
controller: 'someController',
action: 'someAction',
leadfilter: () => $('#filterleads').val()
}
},
Upvotes: 0
Reputation: 337656
The issue is because you only read the value of your select when the page loads, and it's all
by default. You need to change your code so that it reads the value of the select when it makes the request. To do this provide a function to the data
property:
"ajax": {
url: "/leads",
data: function(data) {
data.leadfilter = $("#filterleads").val()
}
},
Note that I removed the ternary as it's not needed. The select
will always have a value.
For more information see the ajax.data
entry in the DataTables documentation.
Upvotes: 1