jeudi 2 avril 2015

Using select dropdowns and checkboxes together to filter datatables

I have a datatable which I need to use both select and checkboxes to filter data. I have no problems getting selects to work, but cannot implement checkboxes in the same filtering. Here is my table:



<table id="example" class="display" width="100%">
<thead>
<tr>
<th>From</th>
<th>Number of days</th>
<th>Direction</th>
</tr>
</thead>

<tfoot>
<tr>
<th class="select">From</th>
<th class="select">Number of days</th>
<th class="select">Direction</th>
</tr>
</tfoot>

<tbody>
<tr>
<td>Vancouver</td>
<td>7</td>
<td>One way</td>
</tr>
<tr>
<td>Vancouver</td>
<td>3</td>
<td>One way</td>
</tr>
<tr>
<td>Vancouver</td>
<td>3</td>
<td>Return</td>
</tr>
<tr>
<td>Vancouver</td>
<td>3</td>
<td>One way</td>
</tr>
<tr>
<td>Calgary</td>
<td>3</td>
<td>One way</td>
</tr>
<tr>
<td>Vancouver</td>
<td>3</td>
<td>One way</td>
</tr>
<tr>
<td>Calgary</td>
<td>4</td>
<td>Return</td>
</tr>


</tbody>
</table>


And here is my jQuery:



$(document).ready( function () {

var table = $('#example').DataTable({
"order": [[ 1, "desc" ]],
"oLanguage": {
"sInfo": "Showing _START_ to _END_ of _TOTAL_ items."
}
});

$("#example tfoot th").each( function ( i ) {

if ($(this).text() == 'Direction') {
var select = $('<div></div>')
.appendTo( $(this).empty() )
.on('change', function () {
var val = $(this).val();
table.column( i )
.search( val ? '^'+$(this).val()+'$' : val, true, false )
.draw();
} );

table.column( i ).data().unique().sort().each( function ( d, j ) {
select.append( '<input type="checkbox" value="'+d+'">'+d+'' );
} );

}

else {
var select = $('<select><option value=""></option></select>')
.appendTo( $(this).empty() )
.on('change', function () {
var val = $(this).val();
table.column( i )
.search( val ? '^'+$(this).val()+'$' : val, true, false )
.draw();
} );

table.column( i ).data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' );
} );
}

} );
} );




Aucun commentaire:

Enregistrer un commentaire