Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using javascript to check if a HTML table cell is empty?

Is these some simple JS code that allows me to check whether a cell is empty.

I am trying to code a function that is called using "onmouseover=func()"; I just cant seem to get the JS code right. Any ideas?

What im ideally trying to work toward is a code that can detemine whether a cell is empty and if so, place a simple value in, like "Cell Empty".

I know it probably sounds simple but i could use a little help. Thanks for any ideas.

like image 616
Paddy McGuire Avatar asked Mar 01 '10 23:03

Paddy McGuire


2 Answers

It depends a little on what will be in there initially. In my experience, tables behave strangely if a cell contains only whitespace, and so a common workaround is to put a   in there to stop it collapsing. Anyway, here's how you'd check:

function elementIsEmpty(el) {
    return (/^(\s| )*$/.test(el.innerHTML);
}

function replaceCell(td) {
    if (elementIsEmpty(td)) {
        td.innerHTML = 'Cell Empty';
    }
}


<td onmouseover="replaceCell(this)"></td>

... though a better way would be to apply the behaviours through Javascript event handlers.

like image 55
nickf Avatar answered Nov 15 '22 08:11

nickf


If you're using jQuery, use the html() method on the element. Given this markup:

<td id="my_cell"></td>

This code will do it:

if ($('#my_cell').html() == '') {
  $('#my_cell').html('Cell Empty');
}
like image 33
Jonathan Julian Avatar answered Nov 15 '22 06:11

Jonathan Julian