Reputation: 8424
I have created a form and I am trying to add validation for a set of select fields that are 'doubly' dynamic - that is to say that, depending on user input, there may be x number of groups with y number of select fields in each. An answer is required for each of the select fields.
The problem I am having is that the form is able to proceed to the next page if fewer than the total existing number of select fields have been answered - if I don't answer any of the select fields, the validation works perfectly, but if even one is answered, I'll still get the alerts but the form will proceed to the next step anyway. Here is a sample of the code ('unchanged' being a value that I've given to a placeholder option in the select):
$(".species_select").each(function(){
if (this.value === "unchanged"){
alert("Please select the species")
}
else{
PROCEED...
};
Conceptually, I understand why this is happening - the condition is being met at least once and is causing the form to proceed. For a form with a fixed number of fields, I would use || between all of the fields in need of validation, but that won't fly under these circumstances.
Perhaps my approach here is entirely wrong... basically, I need the form to treat this as though it can't proceed until every .species_select has a value other than "unchanged".
Your thoughts and expertise are much appreciated.
Upvotes: 2
Views: 47
Reputation: 219
Try using the a flag in the following way:
var proceed = true;
$(".species_select").each(function() {
if (this.value === "unchanged") {
alert("Please select the species");
proceed = false;
}
});
if (proceed) {
// PROCEED...
}
Upvotes: 3
Reputation: 12025
You need to cancel the submission of the form using the preventDefault()
:
$( "#myformID" ).submit(function( e) {
$(".species_select").each(function(){
if (this.value === "unchanged"){
e.preventDefault();
alert("Please select the species")
}
else{
PROCEED...
};
});
Upvotes: 1