I am new to Javascript. Recently I am trying to prepare a checkform function, although the function works, IE mentioned the “msg2” at the end was not declared, may experts please teach me how to make it work? Thanks a lot!
function check_si_form_info(form,mark,edit){
if(mark==11 || mark=="all"){
if(form.login.value==""){
si_check_login.innerHTML="Please enter Login Name!";
si_check_login.style.height="auto";
form.login.style.backgroundColor="#FFD5FF";
return false;
}else if (form.login.value!==""){
var loginname = form.login.value;
xmlhttp=new XMLHttpRequest();
xmlhttp.open('get','si/check_si_loginname.php?loginname='+loginname,true);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
msg2 = xmlhttp.responseText;
if(msg2 == '2'){
si_check_login.innerHTML="Login name is not available!";
si_check_login.style.height="auto";
form.login.style.backgroundColor="#FFD5FF";
return false;
}else if(msg2 == '1'){
si_check_login.innerHTML="";
si_check_login.style.height="0px";
form.login.style.backgroundColor="#FFFFFF";
}
}//200
}//4
}//onreadystatechange
xmlhttp.send(null);
}
if (msg2 == '2'){
return false;
}
}//11
}
To declare a variable, add
var msg2;at the beginning of your Currently, when your end of the function’s body has reached,msg2is not yet defined. Also, you should declare all variables (xmlhttp) usingvar, unless you want them to leak to the global scope.A variable can be defined in some ways:
var msg2;inside the function: This DECLARES a private variable, and initialised it atundefinedvar msg2;outside the function: Declares a variable. Private if the inner function is contained within another scope, egfunction outer(){var msg2;function inner(){...}}. Public otherwise.msg2=null;anywhere: This ASSIGNSnullto variablemsg2. If it has been defined already, see the previous line. Else, it will be publicly defined.Consider your code: