简体   繁体   中英

Why won't JavaScript alert box work in this example?

I am trying to validate 3 fields in a html form using javascript. If any of the fields are empty an alert box appears with a message indicating which fields are empty. This all works fine. I'm having a problem getting the message (msg2) to appear in an alert box when the form has been completed properly. My code is below-I know it's just something simple that I'm missing if anyone can help. Thanks!

 var valid = true;
 var msg="Incomplete form:\n";
 var msg2="Success! There are no null fields.";
 if (  myname== "" ) {
  msg+="You need to fill the name field!\n";
  valid = false;
 }
 if ( emailaddress == "" ) {
  msg+="You need to fill in your email!\n";
  valid = false;
 }

 if ( commentString == "" ) {
  msg+="You need to fill in your comment!\n";
  valid = false;
  }

 if ((!myname=="")&&(!emailaddress=="")&&(!commentString=="")){
  return msg2;
  }

 if (!valid) alert(msg);
  return valid;
}

You're right, it's something simple: return msg2; will not open an alert box. You still have to call alert() somewhere.

i think a little change in your code will solve the problem:

if (!valid) alert(msg);
  return valid;
}

change it to

if (!valid) { 
  alert(msg);
  return valid;
}
if (!valid) {
 alert(msg);
} else {
 alert(msg2);
}
return valid

Maybe somethign like that? And remove the block with if ((!myname=="")&& ...

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