views:

445

answers:

5

Using jquery , how to check whether a table cell is empty or not?

Please help me.

A: 

Try this:

$content = $('#your_cell_id_here').html();

if($content == '')
{
  // yes it is empty
}
else
{
  // no it is not empty
}
Sarfraz
+1  A: 

You can use CSS selectors with the $ function to get a reference to the cell's element, and then use the html function to see whether it has any contents. For instance, if the cell has an ID "foo":

if ($("#foo").html()) {
    // The cell has stuff in it
}
else {
    // The cell is empty
}
T.J. Crowder
Thank you. But all these works only in IE not in Firefox. I checked it now.
Yaswanth
Tested and works in IE7, FF3.5, Chrome3, Safari4, and Opera10. Test page: http://pastie.org/753004 Expected output: "foo has contents / bar is empty" Be sure to allow for whitespace; you may want to trim the string returned by `html`.
T.J. Crowder
A: 

You could add css classes to your table and its rows and columns, then use jquery selectors to get the table item:

if ( !($('#mytable tr.row-i td.column-j').html()) ) { alert("empty"); }
The MYYN
+1  A: 

What do you mean by empty.

//cell maycontain new lines,spaces,&npsp;,... but no real text or other element
$("cellselector").text().trim()=="";

or

//cell has no child elements at all not even text e.g. <td></td>
$("cellselector:empty")
jitter
A: 

You can use the trechnique I posted here

http://www.keithrull.com/2010/06/09/HowToChangeTableCellColorDependingOnItsValueUsingJQuery.aspx

You can use this if you already know the id of the cell you want to check

$valueOfCell = $('#yourcellid').html();

or you can iterate on the cells of the table

$("#yourtablename tr:not(:first)").each(function() {                           
//get the value of the table cell located            
//in the third column of the current row             
var valueOfCell = $(this).find("td:nth-child(3)").html();                          
//check if its greater than zero             
if (valueOfCell == ''){                 
    //place action here
}             
else{                 
    //place action here
}         

});

Keith Rull