Hexana Hexana - 1 month ago 11
HTML Question

Show/Hide Table Rows with Javascript

I have an array of prices that I output to a table with a

foreach
loop.

I'm trying to figure out how to hide rows in the table if a condition is met. The
$status
variable evaluates to "YES" if price is
=> 30
and "NO" if
< 30
.

<script type="text/javascript">
function displayRow(){
var row = document.getElementById("<?php echo $status;?>");
if (row.id == 'YES') row.id= 'none';
else row.display = '';
}
</script>

<?php
if($price > 30.00){
$status = "YES";
}else if($price < 30.00){
$status = "NO";
}

$prices = array ("20", "56", "33", "12", "66", "25", "55");
echo "<table border='1'>";
foreach ($prices as $price) {
echo "<tr id='$status'><td>$price</td></tr>";
}
echo "</table>";
?>

<button onclick="displayRow()" >Show / Hide</button>


I've tried setting the
tr
id
with the appropriate status. So then in the Javascript function I try to pass the
$status
in to
getElementById
which should then display the prices that are
>
than
30
and hide those that are
< 30
.

The button is meant to toggle between display all the data or filter those prices
> 30
.

I know this is a very basic example and have probably made a lot of mistakes, but I'd appreciate any help.

Cheers

Answer

First of all, your code has wrong order (you're trying to read variables before they're even set). Therefore it gives undefined values. Make sure you set the $price and $status before you pass them to the script. Also don't use id as show/hide condition (as id have to be unique), use class instead.

<?php
  $price = 31;

  $prices = array ("20", "56", "33", "12", "66", "25", "55");
  echo "<table border='1'>";
  foreach ($prices as $price) {
    echo "<tr style='display:block;' class='".($price > 30 ? 'YES' : 'NO')."'><td>$price</td></tr>";
  } 
  echo "</table>";
?>

<script type="text/javascript">
  function displayRow(){
    var elems = document.getElementsByClassName("<?php echo ($price > 30 ? 'YES' : 'NO');?>");
    for (var i=0;i<elems.length;i+=1){
      if(elems[i].style.display == 'block'){
        elems[i].style.display = 'none';
      }else{
        elems[i].style.display = 'block';
      }
    }
  }
</script>
<button onClick="displayRow()" >Show / Hide</button>