Skip to content
Advertisement

Using a toggle with jQuery and PHP in a while loop dont work correctly

Got some problems with the jQuery toggler, im using a while loop in PHP and I’m showing database parameters in the page. The problem is that im using a “Details” parameter wich is the largest one, and i want it to be displayed as none, and then click a button to make the data appears(toggle), and when im doing it, only works for even loops of the query, i mean, the first one dont work, but the second works perfectly… Here’s my code:

<?php
$query = "SELECT * FROM datable where user = '".$userSESSION."'";
    if ($result = mysqli_query($db, $query)) {

      while ($row = mysqli_fetch_array($result)) {

?>

And then ive got the toggler where i get my data:

<script >

$('.cuenta_detalles_div').click(function(){

$('.cuenta_detalles_p').toggle();
});

</script>

<div >

<button class="cuenta_detalles_div">Detalles: <i class="fa fa-chevron-down"></i></button>

</div>

<div class="cuenta_detalles_p"><?php echo $row['detalles'];?></div>

};
} 
?>

Tried typical toggle like

<script >

$('.cuenta_detalles_div').click(function(){

 $('.cuenta_detalles_p').toggle();

});

</script>

and other similars but only works for the first row, or even rows but not in all.

Advertisement

Answer

Bit hard to tell from how you’ve provided the code, but it looks like this $('.cuenta_detalles_div').click( is inside the php while loop and before the HTML it applies to.

This means

  • when it runs on the first row, the .cuenta_detalles_div doesn’t exist so does nothing.
  • when it runs on the 2nd row (even row) it actually applies to the first row.
  • 3rd row it applies to the 1st and 2nd row, but the 1st row already has an event handler to toggle, to toggles twice (so appears not to work at all).

Put your event handlers away from the HTML they apply to and wrap them in inside document ready, so there’s only 1 event handler.

$(function() { 
    $('.cuenta_detalles_div').click( ...

This will fix the 1st issue, however it will then apply the click to all of the matching divs, so you need to use this inside the click:

$(function() { 
    $('.cuenta_detalles_div').click(function() {
        $(this).closest("div").next().toggle();
    });
});

(assuming you don’t change your HTML structure)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement