简体   繁体   中英

Javascript Form Submission After Validation

This script functions mostly how I would like it to: alert when a radio checkbox has not been selected. However, if all buttons are selected I need it the form to be submitted...thats where I'm hung up. Right now if all fields and buttons are selected then I still get an alert with var alertMsg. Any ideas?

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();
};

You have a return before the form submit. That may be part of the problem.

Also, you are missing an else on the final if statement.

You're returning false regardless of your validation. Change the end of your code from:

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

to:

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

The length check checks the final value length of alertMsg against what you originally set it to.

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

var alertMsg = "";

//....

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

And please add ; to every statement.

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