1
我試圖製作一個失敗消息,它根據提交時的錯誤將不同的字符串加在一起。但是,即使條件滿足,失敗消息也不會出現。 我想知道我的代碼中的錯誤在哪裏。謝謝。失敗消息未出現在表單驗證事件中
這是在鏈接到HTML文檔的外部JavaScript文件中。
function validationEvent() {
var flag = true;
var alertmsg = "There were errors found in your registration:";
var givenname = document.getElementById("gname").value;
var surname = document.getElementById("sname").value;
var address = document.getElementById("address1").value;
var city = document.getElementById("city").value;
var pcode = document.getElementById("pcode").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var cnum = document.getElementById("cnum").value;
if (givenname == null || givenname == "") {
alertmsg += " Given Name is a mandatory field.";
flag = false;
}
if (surname == null || surname == "") {
alertmsg += " Surname is a mandatory field.";
flag = false;
}
if (address == null || address == "") {
alertmsg += " Address is a mandatory field.";
flag = false;
}
if (city == null || city == "") {
alertmsg += " City is a mandatory field.";
flag = false;
}
if (pcode == null || pcode == "") {
alertmsg += " Postal Code is a mandatory field.";
flag = false;
}
if (email == null || email == "") {
alertmsg += " Email is a mandatory field.";
flag = false;
}
if (phone == null || phone == "") {
alertmsg += " Phone Number is a mandatory field.";
flag = false;
}
if (cnum == null || cnum == "") {
alertmsg += " Credit Card Number is a mandatory field.";
flag = false;
}
if (!vormCredit()) {
alertmsg += " Visa Cards must start with 4 and Mastercard Cards must start with 5.";
flag = false;
}
if (!stateCheck()) {
alertmsg += " Invalid Postal Code.";
flag = false;
}
if (!checkCredit()) {
alertmsg += " Invaid Credit Card Number.";
flag = false;
}
if (!flag) {
alert(alertmsg);
return false;}
else {
alert("Thank you for your subcription.");
return true;}
};
編輯:從'if'循環中刪除'return false',並將其僅添加到if(!標誌)循環中。
不要在你的if語句中調用'return false'。它將退出該功能並停止它的執行。如果有任何錯誤,你的代碼將永遠不會因爲'return'語句而達到'!flag'條件。 –