Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to make table rows collapse if they contain no data. The rows get changed from within a JQuery script. I know they collapse if I place the table inside my HTML. I can create many rows and use display:block or display:none and the rows collapse/display as expected. Here is the markup:

<table style="border-collapse:collapse;">
    <tr style="display:block;">
        <td id="someid">Test</td>
        <td>Some text</td>
    </tr>
</table>

Here is example code I'm using to change the <tr>:

var newtr = "<tr style='display:none;'><td id='someid'></td><td></td></tr>"
$("td#someid").parent().replaceWith(newtr); 

The contents of the rows change, but they don't collapse. I'm using Firebug to see that display:none is being inserted. Is there something else I'm missing?

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

Why not just add hide():

$("td#someid").parent().replaceWith(newtr).hide();

Working example here

share|improve this answer
2  
Why? Because I didn't know I could do that, and so easily. :) I like this. I don't know JQuery/Javascript very much. Thank you! –  rwkiii Jun 26 '12 at 12:36
    
@rwkiii Have a read of jQuery tutorials here and JavaScript tutorials here –  ManseUK Jun 26 '12 at 12:38
add comment

Instead of replacing the tr; if you want to clear the fields and hide the row, I would recommend simply hiding the row and then clearing the cells afterwards, something like this should do the trick:

// this will explicitly set the CSS display property to none and clear the children
$('td#someid').parent().css('display', 'none').children('td').each(function()
{
    $(this).text('');
});

// or you could hide the parent and then clear the children
$('td#someid').parent().hide().children('td').each(function()
{
    $(this).text('');
});
share|improve this answer
    
Using .hide definitely adds some capability for me. I'm not understanding why I would hide the row and also set CSS to display:none. Both of you gave me good answers. The replacement rows are generated in an XSLT stylesheet where I create a JSON object. Your answers having me thinking about simplifying some of my code in the stylesheet. Thank you Richard. –  rwkiii Jun 26 '12 at 12:41
    
You wouldn't need to use both examples, just either/or. I would definitely recommend simplifying things were possible with good use of CSS. –  Richard Jun 26 '12 at 13:26
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.