Search code examples
javascriptjqueryhtmlhtml-tableshow-hide

jQuery .hide method not working on td?


I am creating a table using Javascript and jQuery, and I want it so that when you click the td's on the first row of the table, then the rest of the td's in that column drop down. Let me try to explain it by showing my code. Here is my Javascript:

function createTr (heights) { //heights is just an array of words
    for (var h=0; h<heights.length; h++) { 
        var theTr = $("<tr>", { id: "rowNumber" + h});
        for (var i=0; i<heights.length-3; i++) { 
            theTr.append($("<td>", { "class": "row"+h + " column"+i,
                                     html: heights[h][i]
                                   }));
        }
        $('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table (#newTable), which is written in the html
    }
}

This basically creates td's and each td is similar to this format

<td class="rowh columni">

The parameter 'heights' is just an array, for example, it can be

var heights = [['headerOne', 'headerTwo'], ['someTd', 'anotherTd'],];

and it would create a table using those words, headerOne and headerTwo would be in the first row, someTd and anotherTd would be in the second row.

I want to hide all td's except for the td's on .row0. When I try to hide the td's in the all rows except .row0, it doesn't work. What I tried was putting

$('.row0').hide();

before the $(document).ready( function, after the function and inside the function and neither of them worked. I am basically just calling the createTr function like so

$(document).ready( function() {
    createTr(heights);
});

Any idea why the rows are not hiding?

How do I make it so that it hides after creating the table? I tried placing it as the last part of my Javascript code, that still didn't work. I think that it creates the table slowing and even though the .hide() function is the last part of the Javascript code, it still gets executed before the .hide() code.. How do I make it so that the .hide() method waits until the table is created?


Solution

  • I wanted to show you some code. Here it goes.

    a. This will make sure the table exists before hiding the top row.

    $('#newTable').append(theTr);
    $('.row0').hide();
    

    b. visibility:hidden will take up space in the DOM as opposed to hide() which won't take up space in the DOM (although both present in DOM)

    $('#newTable').append(theTr);
    $('.row0').css('visibility', 'hidden'); //might not destroy your css.