Search code examples
javascriptselectdrop-down-menuhtml-tablehidden

Show hidden rows in table with dropdown


I have something that seems fairly simple but I'm stumped. I want a dropdown within a table that affects how many table rows are shown. By default, only 2 rows are shown. By selecting 4 in the dropdown, 4 rows should be shown. I am only seeing one of the hidden rows show up, and I've tried to wrap the 2 rows in a hidden div as well, no luck. Ideas?

  <table border="1">
          <tr>
            <td class="noBG" colspan="3">
              <select id="displayText" onchange="javascript:toggle();">
                <option>2</option>
                <option>4</option>
              </select>Items
            </td>
          </tr>
          <thead>
            <tr>
              <th>Dates</th>
              <th>Time</th>
              <th>Person</th>
            </tr>
          </thead>
            <tr>
              <td>12/3</td>
              <td>12:45</td>
              <td>John Doe</td>
            </tr>
            <tr>
              <td>12/4</td>
              <td>12:45</td>
              <td>James Doe</td>
            </tr>
            <tr id="toggleText" style="display: none">
              <td>12/4</td>
              <td>12:45</td>
              <td>Janey Doe</td>
            </tr>
            <tr id="toggleText" style="display: none">
              <td>12/4</td>
              <td>12:45</td>
              <td>Janey Doe</td>
            </tr>
        </table>

        <script language="javascript"> 
        function toggle() {
            var ele = document.getElementById("toggleText");
            if(ele.style.display == "block") {
                    ele.style.display = "none"; 
            }
            else {
                ele.style.display = "block";
            }
        } 
        </script>
        ​

Solution

  • Using display: block; doesn't work as the table rows will then displayed not in the right way. But you can toggle the visibility by adding and removing a class, which is defined with display: none;. So you must not switch display: none/block;, but the class.

    This works (incl. jQuery): http://jsfiddle.net/Yuvvc/1/

    You can use following code for JS function:

    function toggle() {
        $.each($('tr[name=toggleText]'), function() {
            $(this).toggleClass("hiddenRow", $(this).attr('class') != "hiddenRow");
        });
    }
    

    With the second parameter (bool) for .toggleClass you can add and remove the class.

    EDIT

    Here a non-jQuery version:

    function toggle() {
        var rows = document.getElementsByName("toggleText");
        for(var i=0; i<rows.length; i++)
        {
            rows[i].className = (rows[i].className == "hiddenRow") ? "" : "hiddenRow";
        }
    }