tags:

views:

486

answers:

4

I have a label that is sometimes empty. How do I set up a conditional statement on the client side to test this?

i have

var label = document.getElementByID("<%=label1.ClientID %>").innerHTMl;

to get the text, but i can't seem to figure out an if..else statment if it is empty or not. label.length == 0; label == null, etc don't seem to work. any help?

+1  A: 

try this:

if(label){ // The label is defined }

Neither the if nor an else on it may execute if its undefined, so best not to use an else on this (seems weird, but I just did a check with firefox)

Matthias Wandel
This is rather elegant. Nice.
Gabriel Florit
A: 

Here's something better:

var id = "<%= label1.ClientID %>";
var label = id.length > 0 ? document.getElementById(id).innerHTML : "";

(Assuming this is Ruby here...)

fig
is that ASP? ahh, it takes me back......
alex
A: 

Use this code:

 var labelID = '<%=label1.ClientID %>';
 if (labelID.length!=0)
     var label = document.getElementByID(labelID).innerHTMl;
 else...
a programmer
2nd line won't work - length is a property, not a function.
fig
Fixed it, thank you.
a programmer
A: 

An empty string is falsy, as is something that's null.

If the label always exists (document.getElementByID("<%=label1.ClientID %>") always returns an html element) then the above should work.

However, the label may only appear to be empty. It could have a blank string inside it. So try this:

var label = document.getElementByID("<%=label1.ClientID %>").innerHTMl;
if (label.replace(/\s/g, '')) {
    // handle it
}
wombleton