In my Laravel application I am using Datatables to enable easy filtering etc. I have managed to develop a input field which searches the generated table. To avoid typing errors, I would like to use the value of a selected option item from a dropdown list. I have been trying some things but I can't get it right.
View:
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Custom Filter</h3>
</div>
<div class="panel-body">
<form method="POST" id="search-form" class="form-inline" role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="search name">
</div>
<div class="form-group">
<label for="category">Category</label>
<select name="category" id="category" class="custom-select">
<option value="reset">-Categorie-</option>
@foreach($adviceCategories as $category => $name)
<option value={{ $category }}>{{ $name }}</option>
@endforeach
</select>
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
</div>
</div>
Partial Controller:
if ($name = $request->get('name')) {
$advicePreparationsQuery->where('advice_protocols.name', 'like', "%$name%");
}
if ($category = $request->get('category')) {
$advicePreparationsQuery->where('advice_protocols.category', 'like', "%$category%");
}
$advicePreparations = $advicePreparationsQuery->get();
$datatables = Datatables::of($advicePreparations)
....
return $datatables->make(true);
And my script:
<script type="text/javascript">
$(document).ready(function() {
oTable = $('#advicePreparations-table').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: "{{ route('advice_protocols.data') }}",
data: function (d){
d.name = $('input[name=name]').val();
d.category = $('option[name=category]').text();
}
},
"columns": [
{data: 'name', name: 'name'},
{data: 'category', name: 'category'},
{data: 'question_name', name: 'goal'},
{data: 'mergeColumn', name: 'mergeColumn'},
{data: 'autheur', name: 'autheur'},
{data: 'active', name: 'active'},
{data: 'acties', name: 'acties', orderable: false, searchable: false},
{data: 'delete', name:'delete', orderable: false, searchable: false}
]
});
$('#search-form').on('submit', function(e) {
oTable.draw();
e.preventDefault();
});
});
</script>
I have tried to change the input type from a dropdown list to an input field to check whether or not the query is wrong, but this works! I have tried changing my script line to: d.category = $('select[name=category]').val();.. but this executes the query when loading the page! This disables the overview of all the categories.. Could someone help me to get the selected value to the query?