0

I have a foreach loop in php that searches through a directory, finds any other directories, and then using hide/show in javascript, the subdirectories names are made into links that drop down to reveal the files inside of that specific subdirectory. I hope that makes sense. The problem I have is that because I am using a loop to find any present subdirectories, I can’t give each of the subdirectories a different id. As a result, all of the links have the id of the first link and when any of them are clicked, the first link always drops down. Do I need to use JQuery for this?

<!--Code for the javascript part:-->
<?php
<script language="javascript">
    function showOrHide(){ 
        var div = document.getElementById("showOrHideDiv");
        if (div.style.display == "block"){ 
                div.style.display = "none";
        }
        else {
            div.style.display = "block";
        }
    }
</script>
?>

<!-- A subdirectory has been found and is called $subDir -->
<!-- Below is the show/hide part of my html/php code -->

<a href="javascript:showOrHide();"><?php echo $subDir;?></a>
<div id="showOrHideDiv" style="display: none">

<!-- The rest of the code that prints the files from the subdirectory -->

</div>
2
  • 4
    Why do you have <?php ... ?> around the script tags? That's not valid PHP, it's HTML! Remove the <?php ... ?>. Commented May 30, 2013 at 21:18
  • 1
    You don't need to use jQuery for this, but you would have to provide different ID's, irregardless of jQuery or not. Commented May 30, 2013 at 21:18

1 Answer 1

2

One approach would be to use a counter and use that to vary the IDs:

<a href="javascript:showOrHide(<?php echo $counter;?>);"><?php echo $subDir;?></a>
<div id="showOrHideDiv_<?php echo $counter;?>" style="display: none">

Then your javascript changes:

<script language="javascript">
  function showOrHide(num){ 
    var div = document.getElementById("showOrHideDiv_" + num);
    if (div.style.display == "block"){ 
      div.style.display = "none";
    }
    else {
      div.style.display = "block";
    }
  }
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

+1 good answer (and for picking up the oversight in my answer as well :D)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.