how to toggle (hide/show) a table onClick of <a> tag in java script

Qadir Hussain picture Qadir Hussain · Mar 29, 2013 · Viewed 121.4k times · Source

I want to show and hide (toggle) the <table> onClick event of the <a>. this is my <a> tag

<a id="loginLink" onclick="toggleTable(true);" href="#">Login</a>

here is my java script function toggleTable(hide)

   <script>
    function toggleTable(hide)
    {
    if (hide) {
       document.getElementById("loginTable").style.display="table";
       document.getElementById("loginLink").onclick = toggleTable(false);

    } else {
       document.getElementById("loginTable").style.display="none";
       document.getElementById("loginLink").onclick = toggleTable(true);
    }
   }
   </script>

and here is my <table> tag

<table id="loginTable" border="1" align="center" style="display:none">

1st time when I click the <a> link it shows my table, but not hiding back when i click it next time. what i m doing wrong.

Answer

hjpotter92 picture hjpotter92 · Mar 29, 2013

You are trying to alter the behaviour of onclick inside the same function call. Try it like this:

Anchor tag

<a id="loginLink" onclick="toggleTable();" href="#">Login</a>

JavaScript

function toggleTable() {
    var lTable = document.getElementById("loginTable");
    lTable.style.display = (lTable.style.display == "table") ? "none" : "table";
}