por por - 3 months ago 13
PHP Question

Getting Javascript to work in PHP while loop

I am trying to use Javascript in the following while loop but its only applying to the first iteration. From reading other posts I have a feelings its got something to do with ID's but I didnt really understand.

Heres my code:

<html>
<head>


</head>

<body>

<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>

<style type="text/css">
#wrapper {
background: #ccc;
display:none
}
</style>

<script type="text/javascript">//<![CDATA[
$(window).load(function(){
$('#button').click(function(){
$('#wrapper').toggle();
})
});//]]>
</script>

<?php
$x = 5;
while($x > 0)
{
?>
<button id="button">ExP</button>
<div id="wrapper" class="open" style="display: none;">
<ul id="list">
<li>Item</li>
</ul>
</div>
<?php
$x = $x-1;
}
?>

</body>
</html>


Any suggestions very much appreciated.

Thanks :)

JDS JDS
Answer

Use class instead of id.

</head>

<body>

<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>

<style type="text/css">
      .wrapper {
      background: #ccc;
      display:none
      }
</style>

<script type="text/javascript">//<![CDATA[
$(window).load(function(){
$('.button').click(function(){
    $(this).next('.wrapper').toggle();
})
});//]]> 
</script>

<?php
$x = 5;
while($x > 0)
{
?>
<button class="button">ExP</button>
<div class="wrapper" class="open" style="display: none;">
  <ul id="list">
    <li>Item</li>
  </ul>
</div>
<?php
$x = $x-1;
}
?>

</body>
</html>
Comments