I'm trying to make some Javascript that shows/hides rows in a data table based on the content of the 4th cell.
Table is as follows:
DATE | DESCRIPTION | PRICE | PHONE | STATUS |
-----------------------------------------------
xxx | yyyyyyyyyyy | 3243 | 32553 | Finished |
xxx | yyyyyyyyyyy | 3243 | 32553 | Suspeded |
xxx | yyyyyyyyyyy | 3243 | 32553 | Active |
xxx | yyyyyyyyyyy | 3243 | 32553 | Finished |
And I have the following code on the onChange function of a dropdown:
function refinesearch() {
$(".data tr").hide(); //hide all rows
var refine = $("#refine1").val(); //retrieve wanted status
if(refine=="All") {
$(".data tr").show(); //show all rows if want to see All
} else {
$(".data tr").each(function() { //loop over each row
if($("td:eq(4)").text() == refine) { //check value of TD
$(this).show(); //show the row
}
});
}
}
Basically, the dropdown has the different statuses in, and if they selected, e.g Finished only the rows that have the status Finished should be shown and all others hidden.
But it doesn't seem to be working correctly. When I select All it works and when I select Finished it shows them all for some reason! Selecting any other value makes all rows hidden! :S - any ideas?
In your loop
$("td:eq(4)")
is selecting table cell in the whole page (not only the row in the loop).You can still do this:
instead of your whole
if
/else
.Answering my own question - thanks for the help Paul!
This will do the trick. selected is an array contains what are the possible td values you going to check. If it's just a string, you can replace the array for loop.
In your loop over each row you miss
$(this)
to refer to your current element.Then, use find() to filter the selection
$(this).find("td:eq(4)").text() == refine
Try using the find() method to restrict your criteria to the current row (yours is selecting all the rows in the table on each loop):