views:

255

answers:

3

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.

A: 

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');
}
Jonathan Julian
This question mentions nothing of jQuery so this doesn't answer the question.
cletus
If you're using jQuery, you need to use `.html()` instead of `.innerHTML`.
Aistina
Oops, you're correct. Edited to be html().
Jonathan Julian
+2  A: 

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 &nbsp; in there to stop it collapsing. Anyway, here's how you'd check:

function elementIsEmpty(el) {
    return (/^(\s|&nbsp;)*$/.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.

nickf
That strange behaviour by the way only applies on IE6/7. It won't render the entire cell, including its markup. Usually the lack of the border or background color is first noticed.
BalusC
A: 

Withouth jQuery (like in the old good times):

function func(e){
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (target.innerHTML === ''){
        target.innerHTML = 'Cell Empty!';
    }
}
Matias
you, sir, have a strange definition of "good".
nickf
sir, I feel you can't understand ironic comments.
Matias