-2

I have this toggle function to make a list item visible and invisible. Without the variable id it works (only the first one opens of course). But with the variable it doesn't work at all. The variable is just a number, added to the list item id, which is well shown in the html code. This is the function that I have:

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$("#button-" . $row['id'] . "").click(function() {
$("#bands-" . $row['id'] . "").toggle();
});
</script>
<?php
echo "<a id='button-" . $row['id'] . "'>bands</a>";

echo "<li id='bands-" . $row['id'] . "' class='clearfix list-group-item' style='display: none;'></li>";
?>

( to echo each line is a bit ugly, I know, but it works :-P )

eisbehr
  • 12,243
  • 7
  • 38
  • 63
  • 1
    Possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Epodax Sep 20 '16 at 13:02
  • Can you show enough code to indicate where $row comes from? Do you have a while or foreach loop somewhere that is not currently included? – The One and Only ChemistryBlob Sep 20 '16 at 13:03
  • Did you check the generated HTML code, if it looks how it should? – gre_gor Sep 20 '16 at 13:08
  • Yes, it´s within the `while($row = mysql_fetch_array( $result )) {`. I did put the `` around it. still doesn´t work, but an smal error is gone (y). – Didi Willems Sep 20 '16 at 13:12
  • Html is fine. Shows button-30 for Id in a item. where bands-30 id for the li item. – Didi Willems Sep 20 '16 at 13:26
  • As eisbehr noticed, the problem is with your JS code not HTML. – gre_gor Sep 20 '16 at 13:28

2 Answers2

0

Your string escaping on JS side is wrong, the rest should work fine. On php side it was correct, because you are inside a string of echo.

$("#button-<?php echo $row['id']; ?>").click(function() {
    $("#bands-<?php echo $row['id']; ?>").toggle();
});
eisbehr
  • 12,243
  • 7
  • 38
  • 63
  • When I changed this I saw that the script function didn´t take the id value. So I put the script inside the `while($row = mysql_fetch_array( $result )) {` Now it works! – Didi Willems Sep 20 '16 at 13:34
0

Instead generating JavaScript code for every row, you should write it once and use the data-id attribute to find the corresponding item.

Your JavaScript should look like:

$(document).on("click", ".bands-button", function() {
    $("#bands-"+$(this).data("id")).toggle();
});

And in your PHP code you put your row id inside the data-id attribute instead of id attribute:

echo "<a class='bands-button' data-id='" . $row['id'] . "'>bands</a>";
echo "<li id='bands-" . $row['id'] . "' class='clearfix list-group-item' style='display: none;'></li>";
gre_gor
  • 6,669
  • 9
  • 47
  • 52