Aishwarya L Aishwarya L - 7 months ago 11
Javascript Question

Expanding and collapsing table rows in jQuery

Here is the

jQuery code
for
expanding and collapsing the rows in a table
but it just doesn't seem to work. Am I going wrong anywhere ?

$('.Complex').click(function() {
if ($(this).hasClass("collapsed")) {
$(this).nextUntil('tr.Complex')
.find('td')
.parent()
.find('td > div')
.slideDown("fast", function() {
var $set = $(this);
$set.replaceWith($set.contents());
});
$(this).removeClass("collapsed");
} else {
$(this).nextUntil('tr.Complex')
.find('td')
.wrapInner('<div style="display: block;" />')
$(this).addClass("collapsed");
}.parent()
.find('td > div')
.slideUp("fast");
});


The following is the jsFiddle

https://jsfiddle.net/uxc3fkcm/

Answer

You have over complicate it. Simply use $.fn.toggleClass() and $.fn.toggle()

$('.Complex').click(function () {
    $(this).toggleClass("collapsed").nextUntil('tr.Complex').toggle();
});

DEMO

If you want sliding motion then use $.fn.slideToggle() instead of $.fn.toggle()

Display or hide the matched elements with a sliding motion.

Comments