问题
I'm trying to take input through two input fields. A minimum field and a maximum field. With the minimum and maximum values I want to look at a certain column and check to see if the value of the cell in that column is between the range. If the cell is not in the range of the minimum and maximum values, I would like to hide the row.
Here's is what I've been working with: (Currently not working as intended.)
$('table').DataTable();
var counterLow = $('#counter-low'),
counterHigh = $('#counter-high');
function filterAge() {
table.columns(1).every(function () {
var min = +counterLow.val(),
max = +counterHigh.val();
this.data().each(function (data, index) {
if (data > min && data < max) {
table.row(index).child.show();
} else {
table.row(index).child.hide();
}
});
});
}
counterLow.on('keyup', filterAge);
counterHigh.on('keyup', filterAge);
table {
width: 100%;
border: 1px solid #ccc;
border-collapse: collapse;
}
table th, table td {
border: 1px solid #ccc;
padding: 8px;
text-align: left;
}
input {
border: 1px solid #ccc;
padding: 8px;
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<input id="counter-low" type="text" placeholder="Minimum age" />
<input id="counter-high" type="text" placeholder="Maximum age" />
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jon</td>
<td>64</td>
</tr>
<tr>
<td>Bill</td>
<td>86</td>
</tr>
<tr>
<td>Joel</td>
<td>12</td>
</tr>
<tr>
<td>Fred</td>
<td>35</td>
</tr>
</tbody>
</table>
回答1:
try this one *Updated
var table = $('table').DataTable();
$.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
return parseInt(data[1]) >= parseInt($('#counter-low').val() || data[1])
&& parseInt(data[1]) <= parseInt($('#counter-high').val() || data[1])
});
$('#counter-low, #counter-high').on('keyup', table.draw);
JSFiddle
回答2:
After a while, I was able to obtain what was needed with a custom filter. This is what I used.
jQuery.fn.dataTableExt.afnFiltering.push(
function (oSettings, aData, iDataIndex) {
var min = +counterLow.val() || table.column(1).data().sort()[0],
max = +counterHigh.val() || table.column(1).data().sort().reverse()[0],
age = +aData[1];
return !!(age >= min && age <= max) &&
!(isNaN(min) || isNaN(max) || isNaN(age));
}
);
Fiddle
来源:https://stackoverflow.com/questions/29973625/how-can-i-filter-between-a-range-of-numbers-and-hide-rows-that-arent-in-the-ran