views:

61

answers:

3

I have a table with row which cab be hidden by user. It's implemented this way:

Markup:

<table>
   <tr>
      <td>
         <table style="margin-left: auto; text-align: right;">
            <tr>
               <td class="stats-hide">
                  <a href="#" onclick="hideStats();">Hide</a>
               </td>
               <td class="stats-show" style="display: none;">
                  <a href="#" onclick="showStats();">Show</a>
               </td>
            </tr>
         </table>
      </td>
   </tr>
   <tr class="stats-hide">
      <td>
        <!-- data -->
      </td>
   </tr>
</table>

And jQuery code:

<script type="text/javascript" language="javascript">
    function hideStats() {
        hideControls(true, $('.stats-hide'));
        hideControls(false, $('.stats-show'));
    }

    function showStats() {
        hideControls(false, $('.stats-hide'));
        hideControls(true, $('.stats-show'));
    }

    function hideControls(value, arr) {
        $(arr).each(function () {
            if (value) {
                $(this).hide();
            }
            else {
                $(this).show();
            }
        });
 }
</script>

How to implement the same behavior with one, single link and one, probably, CSS class?

My idea - store somewhere a boolean variable and toggle controls visibility relatively to this variable. Are there more?

+1  A: 

You can use jquery's toggle to alternate between hiding and showing of objects with one link. You wont need to store any variables.

Galen
Unfortunately `toggle()` doesn't work properly with `tr`..
abatishchev
+2  A: 

Use a toggle as mentioned in the above post but use a "tbody" instead of a "tr" so that rows can be hidden/shown as required.

rajasaur
+1  A: 

Is the row hiding not working properly on IE? What is the version of jQuery and the browser which is troublesome?

I created an example using toggle as suggested by @Galen and it works on Chrome, Firefox, and Safari. I don't have access to IE.

Here's the code:

HTML

<table>
   <tr>
      <td>
         <table class="data">
            <tr>
               <td class="stats-hide">
                  <a href="#" class="toggle-stats">Hide</a>
               </td>
               <td class="stats-show">
                  <a href="#" class="toggle-stats">Show</a>
               </td>
            </tr>
         </table>
      </td>
   </tr>
   <tr class="stats-hide">
      <td>
        Some Data
      </td>
   </tr>
</table>

Javascript

$(".toggle-stats").click(function() {
    $(".stats-hide, .stats-show").toggle();
});
​
Anurag
I tried IE8 and FF3.6 under Windows 7 (x86), jQuery 1.4.2 and `toggle(function, function)`. Thanks! I'll try your version now
abatishchev
I tested these on OSX 10.5 with Chrome 5.0.375.38, Firefox 3.6.3, and Safari 4.0.5. I think multiple links are fine as otherwise you will have to check the link text or some other property to see if stats are currently visible or hidden.
Anurag