首页 > 解决方案 > 如何将 jQuery 过滤器添加到 html 表

问题描述

我正在尝试将 jquery 下拉过滤器添加到从数据库中提取的表中

我提到了一些类似的问题,并从其中一个问题中获得了代码。我可以让下拉前端工作,但被后端卡住了。

报告.php

<div id="container">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> 
</script>
<label for="filter">Gender:</label>
<select class="filter" data-tableId="myTable">
  <option value="all">All</option>
  <option value="male">Male</option>
  <option value="female">Female</option>
</select>
  <body>
  <i style="font-size:24px" class="fa">&#xf019;</i>
  </body>
   </html>
<div class="table-responsive">
    <table id ="myTable" class="table table-striped">
      <thead>
        <tr>
          <th> First Name </th>
          <th> Last Name </th>                  
          <th> Phone </th>
          <th> Email </th>              
          <th> Gender </th>
          <th> Action </th>  
        </tr>
      </thead> 
      <?php
        if (count($report) === 0) {
            echo "<tr>No Reports</tr>";
        } else {
            for ($i = 0; $i < count($report); $i++) {
                echo
                "<tr>
                    <td>{$report[$i]['FName']}</td>
                    <td>{$report[$i]['LName']}</td>
                    <td>{$report[$i]['HPhone']}</td>
                    <td>{$report[$i]['PEmail']}</td>
                    <td>{$report[$i]['Gender']}</td>

                    <td><a class=btn href='read.php?id=".$report[$i]['RegId']."'>Read</a></td>    
                </tr>"; 
            }
        }
      ?>
    </table> 
</div>

main.js

$(".filter").change(function() {
  var filterValue = $(this).val();
  var row = $('.row'); 

  row.hide();
  row.each(function(i, el) {
    if($(el).attr('data-type') === filterValue) {
      $(el).show();
    }
  }); 
});

我想将过滤器放在表格的性别列上。

我确定 main.js 中存在一些错误,并且已经尝试了一段时间但找不到它。我是 jquery 的新手,任何帮助将不胜感激。TIA

标签: phpjqueryfilter

解决方案


您可以使用 AJAX 来处理此任务。

HTML 代码:

<form name="formobject" method="POST" action="">
<input type="hidden" name="formrstatus" value="">
<select class="filter" data-tableId="myTable" onchange="checkValue(this.value)">
  <option value="all">All</option>
  <option value="male">Male</option>
  <option value="female">Female</option>
</select>
</form>

<script>
</script>
function checkValue(id){
$.ajax({
type: "POST",
url:"/someurl",
dataType: 'JSON',
data: {id},
success: function(response) {
                //use this response to fetch table data
},
error: function(XMLHttpRequest, textStatus, errorThrown) {

   }
});
}

/*Use api to fetch the values according to the posted value and return the json encoded value, something like this*/

<?php
$id=encodestring($_POST["id"]);

$sql="select * from sometable where gender='".$id."'";
$result= $mysqli->query($sql);

$vars[] = array($res);

echo json_encode($vars);
?>

推荐阅读