Question : Counting the number of NON EMPTY cells in a table using javascript

I'm implementing a drag and drop type interface that allows me to drag course names from a list and then drop them into empty TD cells within an HTML table, and I would like to be able to somehow keep track of how many courses have been added to the table.  

Is it possible for me to count the number of TD tags that are populated (NOT EMPTY) within and HTML table using javascript?  If so, how?  

For example,  ..

If I know that I can drag up to 25 courses into cells within the HTML table, .. when I drag and drop a course name INTO the table, .. the number of courses should DECREMENT by 1 (to 24).  Likewise, .. If I drag a course OUT of the table (and drag it back to where I got it from) ... the number of courses should then INCREMENT by 1 (to 25), .. etc.

I already have a function in place to intercept the "drop" behavior part of the drag and drop functionality.  I just need to write and insert the function I've described.  Basically, .. the  function (when triggered) should return the number of TD cells that are NOT EMPTY.  

How would I do something like this?  Is it even possible?

- yg





Answer : Counting the number of NON EMPTY cells in a table using javascript

Yes

//get all rows in yard table
var all_td = document.getElementById("tableId").rows;
var counter = 0;
//loop through each row
for(var i=0;i<all_td.length;i++)
{
//loop through each cell in the row
for(var ii=0;ii<all_td[i].cells.length;ii++)
{
   if ( all_td[i].cells[ii].innerHTML.length > 0 )
   {  counter++; }
}
}

alert(counter)
Random Solutions  
 
programming4us programming4us