8

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
2

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');
}

2 Comments

This question mentions nothing of jQuery so this doesn't answer the question.
If you're using jQuery, you need to use .html() instead of .innerHTML.
1

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!';
    }
}

1 Comment

sir, I feel you can't understand ironic comments.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.