User123 User123 - 7 months ago 11
Javascript Question

JQuery - Re-arrange table rows based on select dropdown value

I have a select dropdown and a table. What I'd like to do is when we select from the dropdown menu, a count will be displayed to let us know how many items are in the table (this was done) and also re-arrange the row by bringing the queried/relevant rows to the top. In the example, I'd like for all rows with "Software" to be brought to the top if Software was selected from the dropdown.
Thanks for help!

Here's what I have so far - jquery 1.7.2

https://jsfiddle.net/hv0wfds4/12/

Here's the code:
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>

DK3 DK3
Answer

you can use like that, i hope it helps you.

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); 
 }
}

demo here

Comments