Reputation: 143
I have a DataTable where each row have a tag.
<table id="mytable" class="table table-striped table-bordered dt-responsive" width="100%">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
</thead>
<tbody>
<tr mytag = "tag1">
<td>...</td>
<td>...</td>
</tr>
<tr mytag = "tag2">
<td>...</td>
<td>...</td>
</tr>
</tbody>
</table>
Have a select box with all the tags.
<select id="select_tag" class="select2-original">
<option value="tag1">tag1</option>
<option value="tag2">tag2</option>
</select>
And when a tag is selected, I want to filter the table and only display the rows with the tag but what I did is not working.
var mytable= $('#mytable').DataTable();
$('#select_tag').on('change', function () {
var tagvalue = this.value;
mytable
.rows(function (idx, data, node) {
return node.getAttribute("mytag") == tagvalue? true : false;
})
.draw();
})
Have also tried .hide(), add .data()... nothing works so far...
Upvotes: 0
Views: 280
Reputation: 498
HTML
<div class="row">
<div class="col-md-4 offset-md-4">
<div class="form-control">
<label>Filter</label>
<select id="select_tag" class="form-control select2-original">
<option value="tag1">tag1</option>
<option value="tag2">tag2</option>
</select>
</div>
</div>
</div>
<table id="mytable" class="table table-striped table-bordered dt-responsive" width="100%">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
</thead>
<tbody>
<tr data-mytag = "tag1">
<td>1</td>
<td>Ram</td>
</tr>
<tr data-mytag = "tag2">
<td>2</td>
<td>Shiva</td>
</tr>
<tr data-mytag = "tag2">
<td>3</td>
<td>Vishnu</td>
</tr>
<tr data-mytag = "tag1">
<td>4</td>
<td>Sita</td>
</tr>
</tbody>
</table>
JS
var mytable= $('#mytable').DataTable();
$('#select_tag').on('change', function () {
mytable.draw();
});
$.fn.dataTable.ext.search.push(
function( settings, searchData, index, rowData, counter ) {
var row = mytable.row(index).node();
var filterValue = $(row).data('mytag');
var e = document.getElementById("select_tag");
var filter = e.options[e.selectedIndex].value;
if(filterValue == filter)
return true;
}
);
Upvotes: 1