简体   繁体   中英

javascript - find the length of a label and if it is empty?

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?

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

Here's something better:

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

(Assuming this is Ruby here...)

Use this code:

 var labelID = '<%=label1.ClientID %>';
 if (labelID.length!=0)
     var label = document.getElementByID(labelID).innerHTMl;
 else...

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM