frassedylan
frassedylan

Reputation: 13

jQuery toggle - show only one div

I'm an absolute beginner in javascript and jQuery, trying to learn. I have some tables that are toggled with this jQuery:

$(document).ready(function() {
    $('th').click(function() {
        $(this).parents('table').find('td').slideToggle("fast");
    });
});

I would like to only show one table at a time, so that if you show the first table and then show another, the first one closes. I would be very thankful for any guidance. Full code here: http://jsfiddle.net/qHGDF/1/

Upvotes: 1

Views: 1014

Answers (6)

kidwon
kidwon

Reputation: 4504

You could try this: http://jsfiddle.net/5hDVS/

$(document).on('click','div.datagrid',function() {
     $('table td',this).slideToggle("fast");
     $('td',$(this).siblings('div.datagrid')).slideUp('fast');
});

Upvotes: 0

Patrick Ferreira
Patrick Ferreira

Reputation: 2053

If you'll have too many entries on your tables, and for optimisation purposes on the rendering, slide the <tbody> element instead of <td>

Upvotes: 0

superUntitled
superUntitled

Reputation: 22527

You need to hide the ones that are open, one way to do this is to find all the td's that are not the one that needs to be shown and run slideUp(): http://jsfiddle.net/qHGDF/4/

$('th').click(function() {
    var thetd =  $(this).parents('table').find('td');
    $('table  td').not(thetd).slideUp("fast");
    $(thetd).slideToggle("fast");
});

Upvotes: 1

Manish Mishra
Manish Mishra

Reputation: 12375

in order to do that, you need to hide all the tds first

var $ = jQuery.noConflict(true);
        $('th').click(function() {
            $('table  td').hide(300);
            $(this).parents('table').find('td').slideToggle("fast");
        });

fiddle

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You can always slide up all other td's

$(document).ready(function() {
    $('th').click(function() {
        $("td").slideUp("fast");
        $(this).parents('table').find('td').slideToggle("fast");
    });
});

Upvotes: 0

Rodrigo Siqueira
Rodrigo Siqueira

Reputation: 1154

Try this

  $('th').click(function() {
    $(".datagrid").children("table").find("td").slideUp();
    $(this).parents('table').find('td').slideToggle("fast");
  });

Upvotes: 1

Related Questions