如何基于所选值筛选小于表格单元格值的HTML表格

问题描述 投票:0回答:1

我想根据所选值从数据库中过滤表的显示。

我想通过比较整数/字符串值来在每行的第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";
        }
      }
    }
  }

enter image description here

javascript html jquery html-table
1个回答
0
投票
首先通过转换为整数然后进行比较来解决,这要感谢@isherwood
© www.soinside.com 2019 - 2024. All rights reserved.