user1261582
user1261582

Reputation: 5

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

Upvotes: 0

Views: 6944

Answers (4)

xdazz
xdazz

Reputation: 160843

var alertMsg = "";

//....

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

And please add ; to every statement.

Upvotes: -1

j08691
j08691

Reputation: 207911

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.

Upvotes: 1

Robert
Robert

Reputation: 2471

Your returning before the form submit line, so it will never be called.

Upvotes: 1

Jeremy Goodell
Jeremy Goodell

Reputation: 18962

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.

Upvotes: 2

Related Questions