验证后的Javascript表单提交

时间:2012-05-30 02:37:55

标签: javascript html validation

此脚本主要用于我的工作方式:在未选中单选复选框时发出警报。但是,如果选择了所有按钮,我需要提交表格...那就是我挂断的地方。现在,如果选择了所有字段和按钮,那么我仍然会收到var alertMsg的警报。有什么想法吗?

function submitform() {
    var sizeChoice = ""
    var size = document.store.on1.length
    var fontChoice = ""
    var len = document.store.on2.length
    var materialChoice = ""
    var material = document.store.on3.length
    var treatmentChoice = ""
    var treatment = document.store.on4.length
    var a = document.forms["store"]["item_name"].value;
    var alertMsg = "Please Choose a:"
    for(i = 0; i < size; i++) {
        if(document.store.on1[i].checked) {
            sizeChoice = document.store.on1[i].value
        }
    }
    for(i = 0; i < len; i++) {
        if(document.store.on2[i].checked) {
            fontChoice = document.store.on2[i].value
        }
    }
    for(i = 0; i < material; i++) {
        if(document.store.on3[i].checked) {
            materialChoice = document.store.on3[i].value
        }
    }
    for(i = 0; i < treatment; i++) {
        if(document.store.on4[i].checked) {
            treatmentChoice = document.store.on4[i].value
        }
    }
    if(a == null || a == "") alertMsg += "\n" + "Name" + "\n";
    if(sizeChoice == "") {
        alertMsg += "Size" + "\n"
    }
    if(fontChoice == "") {
        alertMsg += "Font" + "\n"
    }
    if(materialChoice == "") {
        alertMsg += "Material" + "\n"
    }
    if(treatmentChoice == "") {
        alertMsg += "Treatment" + "\n"
    } {
        alert(alertMsg)
    };
    return false;
    document.forms["form"].submit();
};

4 个答案:

答案 0 :(得分:2)

您在表单提交前返回。这可能是问题的一部分。

此外,您在最终的if语句中缺少其他内容。

答案 1 :(得分:2)

无论您的验证如何,您都会返回false。更改代码的结尾:

if(treatmentChoice == "") {
    alertMsg += "Treatment" + "\n"
} {
      alert(alertMsg)
};
return false;
document.forms["form"].submit();

为:

if(treatmentChoice == "") {
    alertMsg += "Treatment" + "\n"
}
if(alertMsg.length > 16) {
    alert(alertMsg);
    return false;
} else {
    document.forms["form"].submit();
}

长度检查会根据您最初设置的内容来检查alertMsg的最终值长度。

答案 2 :(得分:1)

您在表单提交行之前返回,因此永远不会被调用。

答案 3 :(得分:-1)

var alertMsg = "";

//....

if(alertMsg) {
    alert("Please Choose a:" + alertMsg);
} else {
    document.forms["form"].submit();
}

请在每个声明中添加;