JavaScript determines whether the program code is empty

Source: Internet
Author: User


Whether the variable is empty

The following is the result of the IF (TMP) {} decision:

The code is as follows Copy Code

if (TMP) if (tmp!=null)

//false//false when TMP is undefined

Vartmp;//false//false

Vartmp=0;//false//true

Vartmp=10;//true//true

Vartmp= "";//false//true

vartmp= "DDD";//true//true

Vartmp=0.0;//false//true

Vartmp=newstring ();//true//true

Conclusion: To determine whether TMP is undefined or null, you can use if (tmp!=null) and not use if (TMP)

Null function is judged

The code is as follows Copy Code

Functionisempty (Val)
{
Switch (typeof (Val))
{
Case ' string ':
Returnutils.trim (Val). Length==0?true:false;
Break
Case ' number ':
returnval==0;
Break
Case ' object ':
Returnval==null;
Break
Case ' array ':
returnval.length==0;
Break
Default
Returntrue;
}
};

Determines whether the input string is empty

Too simple, the value is judged to be equal to "", the example function is as follows:

The code is as follows Copy Code
Functionisnull (ctlid,ctlname) {
Varctl=document.getelementbyid (Ctlid);
if (ctl.value== "") {
Alert (ctlname+) cannot be empty. ");
Ctl.focus ();
Returntrue;
}
Returnfalse;
}
If you judge directly, write this:
if (document.getElementById (ctlid). value== "") {...}


To determine whether a text box is empty

  code is as follows copy code

<script Language= "java Script" >
function Check () {
  if (form1.user.value== "") | | (form1.pwd.value== "")) return false;
}
</script>


<form name= "Form1" method= "Post" action= "ls.php" >
User name: <input name= " User "type=" text id= "user" ><br>
Password: <input name= "pwd" type= "password" id= "PSW" ><br>
< Input type= "Submit" name= "Submit" value= "confirm" onclick= "return check ();" >
</form>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.