繁体   English   中英

jQuery-根据选择下拉列表值重新排列表行

[英]JQuery - Re-arrange table rows based on select dropdown value

我有一个选择下拉列表和一个表。 我想做的是,当我们从下拉菜单中选择时,将显示一个计数,以让我们知道表中有多少项(已完成),并通过带来查询/相关的内容来重新安排行行到顶部。 在示例中,如果从下拉列表中选择了“软件”,我希望所有带“软件”的行都显示在顶部。 感谢帮助!

到目前为止,这是我所拥有的-jQuery 1.7.2
https://jsfiddle.net/hv0wfds4/12/

这是代码:JS:

function filterProduct(){
  $product_dd = $('#product_select').val();
  if($product_dd =="All"){
    $('#count_co_prod').text($('#part_list_body tr').length);     
  } else {
  products = $('tr').find("td:contains('"+$product_dd+"')").length;
  $('#count_co_prod').text(products); 
  }
}

HTML

<select id="product_select" onchange="filterProduct()" style="width:300px">
<option value="All">All</option>
<option value="Communications">Communications</option>
<option value="Software">Sofware</option>
</select>

<p>Count Product Category: <span style="color:red" id="count_co_prod"></span></p>

<table id="part_list" width="500px" border="1">
  <thead>
    <tr>
      <th>Company</th>
      <th>Product Category</th>
    </tr>
  </thead>
  <tbody id="part_list_body">
    <tr>
      <td>1C</td>
      <td>Communications</td>
    </tr>
    <tr>
      <td>2S</td>
      <td>Software</td>
    </tr>
  ...
  </tbody>
</table>

您可以那样使用,希望对您有所帮助。

function filterProduct(){
 $product_dd = $('#product_select').val();
 if($product_dd =="All"){
  $('#count_co_prod').text($('#part_list_body tr').length);       
 } else {
    products = $('tr').find("td:contains('"+$product_dd+"')").length;
    var tablerow = $('tr').find("td:contains('"+$product_dd+"')").parent();
 $(tablerow).remove();
 $("#part_list_body").prepend(tablerow);
 $('#count_co_prod').text(products); 
 }
}

在这里演示

这应该做

function filterProduct(){
  var product_dd = $('#product_select').val();   
  if(product_dd =="All"){
    var els = $('tbody tr').sort( function(a,b){
        return $(b).find('td:first').text() < $(a).find('td:first').text();
    });
    $('tbody').append(els);
    $('#count_co_prod').text($('#part_list_body tr').length);     
  } else { 
    var products = 0;
    $('tbody tr').each( function(){
        if($(this).find('td:last').text() != product_dd){
            $(this).prop('sortOrder', -1);
        } else {
            products++;
            $(this).prop('sortOrder', 1);
        }
    });
    var els = $('tbody tr').sort( function(a,b){
        return parseInt($(b).prop('sortOrder')) -  parseInt($(a).prop('sortOrder'));
    });
    $('tbody').append(els);
    $('#count_co_prod').text(products);
  }
}

在这里工作的JSFiddle: https ://jsfiddle.net/GSarathChandra/hv0wfds4/26/

使用动态表创建是唯一可行的方法,因为您没有使用任何数据库来对数据进行硬编码,请尝试在数据中添加array []并使用动态创建html表或搜索Datatable及其网格功能。

建议的链接,

参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM