我想根据所选值从数据库中过滤表的显示。
我想通过比较整数/字符串值来在每行的第7个单元格索引小于选定值时显示表行。
我找到了很多符合条件或包含条件的示例,但是我不知道小于或大于,目前我的代码显示表格,但不能正常工作。
如果它也可以使用jQuery,我很高兴。
<table id="carTable" class="table table-striped">
<thead>
<tr class="header">
<th>ID</th>
<th>Make</th>
<th>Model</th>
<th>Type</th>
<th>Seats</th>
<th>Color</th>
<th>Location</th>
<th>Price/Day
<select id='filterText' style='display:inline-block' onchange='filterPrice()'>
<option value="all" selected>All</option>
<option value='69'> < 69 </option>
<option value='100'> < 100 </option>
<option value='200'> < 200 </option>
<option value='500'> < 500 </option>
</select>
</th>
</tr>
</thead>
<tbody id="carsTable">
{%for car in cars%}
<tr>
<td>{{ car[0] }}</td>
<td>{{ car[1] }}</td>
<td>{{ car[2] }}</td>
<td>{{ car[3] }}</td>
<td>{{ car[4] }}</td>
<td>{{ car[5] }}</td>
<td>{{ car[6] }}</td>
<td>{{ car[7] }}</td>
</tr>
{%endfor%}
</tbody>
</table>
我的功能看起来像这样
function filterPrice() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("filterText");
filter = input.value;
table = document.getElementById("carTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[7];
if (td) {
cellValue = td.innerHTML;
if (cellValue <= filter) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
答案 0 :(得分:1)
首先通过转换为整数然后进行比较来解决,这要感谢@isherwood
function filterPrice() {
// Declare variables
var input, filter, table, tr, td, i, cellValue;
input = document.getElementById("filterText");
filter = parseInt(input.value);
table = document.getElementById("carTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[7];
if (td) {
cellValue = parseInt(td.innerHTML);
if (cellValue <= filter) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}