Sunday, May 15, 2011

Hide table row with javascript

Learn how to dynamically hide table row with a help of javascript! In this tutorial there are two samples:

  • How to hide or show entire HTML table on the fly

  • How to hide or show row in HTML table

To find more helpful javascript effect tutorials follow the link.

Hide HTML table on the fly with javascript

Demo:

show/hide Table
Simple table Row 1 Column2
Row 2 Column1 Row 2 Column2

With a clik on link "show/hide Table" entire HTML table is hided or showed. When a link is clicked jscript function elementHideShow with parameter simpleTable which is id of table. Then function elementHideShow hide table if table is showed (display property is block) or show table if table is hided (display property of table is none and become block).

Here is a sample code:


<script language="javascript">
    function elementHideShow(elementToHideOrShow) 
    {
        var el = document.getElementById(elementToHideOrShow);
        if (el.style.display == "block") {

            el.style.display = "none";
        }
        else 
        {
            el.style.display = "block";
        }
    }         
</script>

    <a href="javascript:elementHideShow('simpleTable');">show/hide Table</a>
    
    <table style="width:300px; display:block;" id="simpleTable" border="1">
        <tr>
            <td>
                Simple table</td>
            <td>
                Row 1 Column2</td>

        </tr>
        <tr>
            <td>
                Row 2 Column1</td>
            <td>
                Row 2 Column2</td>

        </tr>      
    </table>

Hide table row with javascipt

Demo:

show/hide Row
Simple table Row 1 Column2
Row 2 Column1 Row 2 Column2

In this case only table row is hided when a link "show/hide Row" is clicked. When use click this link a function elementHideShow is called with a parameter Row2Column1. This parameter is id of row in a table so entire row in HTML is hided (or showed if a row is already hided).

Here is a code:


<script language="javascript">
    function elementHideShow(elementToHideOrShow) 
    {
        var el = document.getElementById(elementToHideOrShow);
        if (el.style.display == "block") {

            el.style.display = "none";
        }
        else 
        {
            el.style.display = "block";
        }
    }         
</script>

    <a href="javascript:elementHideShow('Row2Column1');">show/hide Row 2</a>
    
    <table border="1">
        <tr style="width:300px; display:block;">
            <td style="width:50%" >
                Simple table</td>
            <td>
                Row 1 Column2</td>
        </tr>
        <tr id="Row2Column1" style="width:300px; display:block;">
            <td style="width:50%">
                Row 2 Column1</td>
            <td>
                Row 2 Column2</td>
        </tr>      
    </table>

1 comment:

Anonymous said...

Thank you very much.