The Toggle script in a loop only works for a first iteration

advertisements

Here is my php/javascript code. I have tried to write the script inside the loop but it doesn't work. This generates two buttons, one for local team, while processing local team, and the second for road team, while processing road team. These buttons show information contained in a div of a different class. For some reason, it works only for the local team, which its the first iteration of the loop.

I have read a lot about people using id's instead of classes, but this is not my case. I am quite lost.

Thank you very much for your help.

<script>
    $(".showavgloc").click(function(){
        event.preventDefault();
        $(".averageloc").slideToggle("slow");
    });
    $(".showavgvis").click(function(){
        event.preventDefault();
        $(".averagevis").slideToggle("slow");
    });
</script>
<?php
foreach ($teams as $team) {
    if ($page=="game") {
        if ($team==$locteam) {
            echo "<button class='showavgloc'>Show average player</button>";
        }
        if ($team==$visteam) {
            echo "<button class='showavgvis'>Show average player</button>";
        }
    }
    if ($team==$locteam) {
        echo "<div class='averageloc' style='display:none'>This div has to be shown/hidden for local team</div>";
    }
    if ($team==$visteam) {
        echo "<div class='averagevis' style='display:none'>This div has to be shown/hidden for road team</div>";
    }
}
?>


Try to do this:

after that php code, and before close it ( before this "?>"), do an "echo" that contains:

<script>
    $(".showavgloc").click(function(){
        event.preventDefault();
        $(".averageloc").slideToggle("slow");
    });
    $(".showavgvis").click(function(){
        event.preventDefault();
        $(".averagevis").slideToggle("slow");
    });
</script>

and try to use it as you want. This might help in some cases, because when you use the jQuery library and then you generate html throw code, the DOM keeps with the "initial" version an jQuery can't work properly because never find the controls. The right order is : Print controls and then bind jQuery events.

Good luck