Reputation: 99
I'm using the dataTables jQuery plugin on a table, but I want to add a Filter Column drop-down box before the search box. I see documentation for adding drop-down boxes to individual columns but I want to add just one drop-down box which has all the column names. I am new to this and would greatly appreciate any help. I have added my code below.
HTML:
<select id='mySelector'>
<option value="">Please Select</option>
<option value='Name'>Name</option>
<option value='Highlights'>Highlights</option>
<option value='Area'>Area</option>
</select>
<table class="table table-striped" id="myTable" cellspacing="0">
@{int rowNo = 0;}
<thead>
<tr>
<th>
Item
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Highlights)
</th>
<th>
@Html.DisplayNameFor(model => model.Area)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Select((x, i) => new { Data = x, Index = i + 1 }))
{
rowNo++;
<tr>
<td>
@rowNo.ToString("000")
</td>
<td>
@Html.DisplayFor(modelItem => item.Data.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Data.Highlights)
</td>
<td>
@Html.DisplayFor(modelItem => item.Data.Area)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Data.id}) |
@Html.ActionLink("Details", "Details", new { id = item.Data.id}) |
@Html.ActionLink("Delete", "Delete", new { id = item.Data.id})
</td>
</tr>
}
</tbody>
</table>
JS:
$('#myTable').DataTable();
Upvotes: 1
Views: 3415
Reputation: 844
Try this, I add the dropdown option to select which column to search.
var table = $('#example').DataTable({
dom : 'l<"#add">frtip'
})
$('<label/>').text('Search Column:').appendTo('#add')
$select = $('<select/>').appendTo('#add')
$('<option/>').val('All').text('All').appendTo($select);
$('<option/>').val('0').text('Seq').appendTo($select);
$('<option/>').val('1').text('Name').appendTo($select);
$('<option/>').val('2').text('Position').appendTo($select);
$('<option/>').val('3').text('Office').appendTo($select);
$('<option/>').val('4').text('Start Date').appendTo($select);
$('<option/>').val('5').text('Salary').appendTo($select);
$('input[type="search"]').on( 'keyup change', function () {
var searchValue = $(this).val();
var columnSearch = $select.val();
if(columnSearch == 'All'){
table.search(searchValue).draw();
} else {
table.columns(columnSearch).search(searchValue).draw();
}
});
Here is the demo. for the code above.
Upvotes: 3