Coding Tips (JavaScript/CSS/VBA/Win32)

Useful code snippets, tips and some Windows applications

How to Hide/Show HTML Table Rows


We'll show how to hide all the rows in a table except the first one with a JavaScript function.

Here is the JavaScript function.

var hide= true;

function toggleRows(tableId, tag){

	tbl = document.getElementById(tableId);
	var len = tbl.rows.length;
	var vStyle = (hide)? "none":"";

	for(i=1 ; i< len; i++){
		 tbl.rows[i].style.display = vStyle;
	 }

	if(hide)
		tag.innerHTML = "Click here to show rows";
	else
		tag.innerHTML = "Click here to hide rows";
	hide= !hide;
}

Code Explanation

The table we use must have an id attribute. If the table id is "myTable", we use the following call to the function: toggleRows("myTable", this). We pass the table id and the p tag object to the function.
We use a global variable hide to store the state of the table.
First thing we do is calculate the rows length and store it in the len variable.
The vStyle variable is used to store the required style of the table rows. It is set to none to hide a row. To show the row again, it is set to a blank.
Then we go through the all the rows of the table starting with the second one, obviously, and set their style as required.
The next portion of the code deals with changing the label above the table.
The last thing we do is toggle the value of the hide variable.

See an example here.