JavaScript button for Show / Hide info on click not working for my Javascript / PHP code

42 Views Asked by At

I have created a search engine for my web site that finds specific courses I'm searching for. For each course I want to add a "show / hide"-button that can show (or hide) the information for each course. However I'm struggling to get the button working, as it is constantly showing the info, but not able to hide it (see attachment). I'm using both some Javascript, PHP and SQL queries as you can see. Anyone can see where the error is? :-) NB! Don't mind the Norwegian language that you will see some places in the picture.. :-)

This is my code:

$db = kobleTil();

$search = $_POST['search'];
$sok = "SELECT * FROM course WHERE coursenameLIKE '%$search%'" ; 
$resultSearch = $db->query($sok);

$counter= 0;
while($nextRow= $resultSearch->fetch_assoc()){
    $info = $nextRow['info'];
    echo "Kurs-ID: <b>" . $nextRow['course_id'] . "</b>";
    echo "<br>Navn: <b>" . $nextRow['coursename'] . "</b>";
    echo "<br>Pris: <b>" . $nextRow['price'] . "</b>";
    echo "<br>Påmeldingsfrist: <b>" . $nextRow['date'] . "</b>";
    echo "<br>Maks antall: <b>" . $nextRow['max'] . "</b><br>";
    $counter++;

    ?>
    <button onclick="myFunction<?php echo $counter; ?>()">Show/hide info</button>
    <div id="showInfo<?php echo $counter; ?>">
    <?php echo "<b>". $info. "</b>"; ?> 
    </div>
    
    <?php
    echo "<br><a href='utlopt.php'>Go to registration?</a>";
    echo "<hr />";
}
?>

<script>
<?php   
for ($t = 1; $t <= $counter; $t++) {
    $temp = 'showInfo'.$t;
    echo "function myFunction$t() {
  var x = document.getElementById($temp);
  if (x.style.display === 'none') {
    x.style.display = 'block';
  } else {
    x.style.display = 'none';
  }";
};
?>

</script>

Here are the result from the code. The show / hide buttons are constantly showing the course info, but not able to hide it

1

There are 1 best solutions below

1
imvain2 On

Luckily with javascript you don't need dynamic class names/IDs etc to toggle content. With your layout you have the div directly after the button, making it the next sibling.

So you can give the div a class that automatically hides it via CSS. Then delegate the click handler to the document and just detect what was clicked. If the clicked element has a specific class, then simply toggle a class on the next sibling element. The active class would simply be used to change the display to block.

document.addEventListener("click",(e) => {
   const el = e.target;
   if(el.classList.contains("btnShow")){
      el.nextElementSibling.classList.toggle("active")
   }
});
.content-div{display:none;}
.content-div.active{display:block;}
<button class="btnShow">Show/hide info</button>
<div class="content-div">
    Content 1
</div>
<hr>
<button class="btnShow">Show/hide info</button>
<div class="content-div">
    Content 2
</div>