0

I have several div's using an id obtained from a query, this id is then used in a function to show/hide the div onclick. My problem is using the below code the div seems to open with "show" changing to "hide" (clicking "hide" does not change to "show") but the contents of the div is not shown.

javascript:

function toggle(id) {
   var ele = document.getElementById(id);
   var text = document.getElementById(id);
             if(ele.style.display == "block") {
             ele.style.display = "none";
             text.innerHTML = "show";
 }
 else {
    ele.style.display = "block";
    text.innerHTML = "hide";
 } 
 } 

php:

echo "Info: <a id='$id' href='javascript:toggle(\"$id\");'>show</a>";
      echo"<div id='$id' style='display: none'></div>";
1
  • liunian is right, never use an id twice Commented Sep 17, 2012 at 6:28

2 Answers 2

2

You are using same ID twice which is wrong, adding a _toggle to your a tag's id can fix this.

Change your codes to this and it may work:

Javascript:

function toggle(id) {
    var ele = document.getElementById(id);
    var text = document.getElementById(id + '_toggle');
    if(ele.style.display == 'block'){
        ele.style.display = 'none';
        text.innerHTML = 'show';
    }else{
        ele.style.display = 'block';
        text.innerHTML = 'hide';
    }
}

php:

echo 'Info: <a id="'.$id.'_toggle" href="javascript:toggle(\''.$id.'\');">show</a>';
echo '<div id="'.$id.'" style="display: none;"></div>';
Sign up to request clarification or add additional context in comments.

Comments

0

you are using the same id for both href and div

php:

  echo "Info: <a id='$id' href='javascript:toggle(\"$id\");'>show</a>";
  echo"<div id='$id' style='display: none'></div>";

change the $id of the A .

Comments

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.