Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle (hide/show) a table onClick of <a> tag in Javascript

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 Javascript 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">

The first time when I click the <a> link it shows my table, but not hiding back when I click it next time. What am I doing wrong?

like image 737
Qadir Hussain Avatar asked Mar 29 '13 06:03

Qadir Hussain


People also ask

How do I hide a tag in JavaScript?

To hide an element, set the style display property to “none”. document. getElementById("element").

How do you show and hide a table in HTML?

Approach 1: Select the header using a CSS selector and modify the style property such that the value of the display property is set to none. This will hide the selected table header element from the page. Example: html.

How do you toggle something in JavaScript?

We can toggle a button using conditional statements like if-else statement in JavaScript. We can toggle almost all the properties of an element like its value, class, id, and color in JavaScript. To change any property of an element, we need to get the element using its id or class.


1 Answers

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";
}
like image 105
hjpotter92 Avatar answered Oct 07 '22 18:10

hjpotter92