根据选择的搜索条件和搜索关键字显示结果表

时间:2019-11-25 05:39:47

标签: javascript drop-down-menu

假设我的桌子包含学生列表。要搜索学生,我在要选择的条件上有一个下拉列表,例如,按照ID进行搜索,按家乡搜索,按性别搜索,按最高GPA进行搜索等。选择条件后,我想要搜索时,我继续输入关键字。

当前,我有2个变量,category是存储要选择的选项/条件的变量,keyword是我在输入框中输入的单词。

如果我想将输入的关键字与所选条件列中的所有对象进行比较,该怎么办?假设我选择了按家乡搜索,当我输入“新建”时,结果表将显示所有带有“新”字样的家乡搜索结果。我已经使用过toUpperCase(),因为我不想使用区分大小写的搜索。

1 个答案:

答案 0 :(得分:1)

请在下面找到工作过滤器功能的代码段,此处我使用搜索字段以及下拉菜单来选择类别,我想这会有所帮助:

$(document).ready(function() {
  this.json = {
    "Students": [{
        "id": "1",
        "hometown": "London",
        "gender": "Male",
        "GPA": "8",
        "name": "Lee",
      },
      {
        "id": "2",
        "hometown": "NY",
        "gender": "Male",
        "GPA": "9",
        "name": "Shaldon",
      }, {
        "id": "3",
        "hometown": "Paris",
        "gender": "Female",
        "GPA": "7",
        "name": "Julie",
      }
    ]
  };
  
  this.renderTable = function(Students) {
    var tbody = document.getElementById('tbody');
    tbody.innerHTML = "";
    for (var i = 0; i < Students.length; i++) {
      var tr = "<tr>";
      tr += "<td>ID</td>" + "<td>" + Students[i].id + "</td></tr>";
      tr += "<td>HomeTown</td>" + "<td>" + Students[i].hometown + "</td></tr>";
      tr += "<td>Gender</td>" + "<td>" + Students[i].gender + "</td></tr>";
      tr += "<td>GPA</td>" + "<td>" + Students[i].GPA + "</td></tr>";
      tr += "<td>NAME</td>" + "<td>" + Students[i].name + "</td></tr>";
      tr += "<hr>";
      tbody.innerHTML += tr;
    }
  }

  this.renderTable(this.json.Students);

  console.log(this.json.Students);
  //code for filtering//
  this.Filter = function() {
    var search = document.getElementById('search');
    var category = document.getElementById('category');
    var filteredObj = this.json.Students;
    filteredObj = $.map(this.json.Students, function(val, key) {
      if (search.value === val[category.value]) return val;
    });
    filteredObj.length>0 ? this.renderTable(filteredObj) : this.renderTable(this.json.Students);
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<p></p>

<input id="search" type="search">
<select id = "category">
<option value = "select">select</option>
   <option value = "id">ID</option>
   <option value = "hometown">HomeTown</option>
   <option value = "gender">Gender</option>
   <option value = "GPA">GPA</option>
   <option value = "name">NAME</option>
  </select>
<button onclick="Filter()">Filter</button>

<table>
  <tbody id="tbody"></tbody>
</table>