0

I have a table that is populated from a JSON object. The result is a table with an uneven number of cells in each row. I'm working on a script to automatically append empty cells to each row so that there is a uniform number. My problem is figuring out the length of the longest row in the table. Below is my attempt at this. However, I keep getting errors that the row is undedefined (e.g. "cannot read property length of undefined"). What have I done wrong?

function countCells() {
var columnCount;
$("#MarketsTable tr").each(function () {
    columnCount = Math.max(columnCount, $(this).cells.length);
})
return columnCount;
}

2 Answers 2

3

I've made two changes to the code below. First I've declared columnCount as 0 in case the issue is related to passing NaN to Math.max. Secondly $(this).cells has been replaced with its vanilla counterpart.

function countCells() 
{
    var columnCount = 0;
    $("#MarketsTable tr").each(function () {
        columnCount = Math.max(columnCount, this.cells.length);
    })
    return columnCount;

}

3
  • Good catch. JavaScript does indeed return NaN from the Math.max function in this case. Jan 31, 2012 at 22:38
  • Good catch indeed. I just figured that out the hard way.
    – hughesdan
    Jan 31, 2012 at 22:39
  • I gave mblase75 credit for the answer since he was first. But you deserve a +1 for NaN.
    – hughesdan
    Jan 31, 2012 at 22:46
2

You're mixing basic DOM/JavaScript with jQuery.

Replace $(this).cells.length with either $(this).children('td').length or this.cells.length

http://api.jquery.com/children/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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