I have a function to sum values a form and compare with a another value.
HTML :
<input class="fieldToValidate" name="option-quantity">
<input class="fieldToValidate" name="option-quantity">
<input class="fieldToValidate" name="option-quantity">
<input class="fieldToValidate" name="option-quantity">
<button type='button' id="button-cart">Add To Cart</button>
<div class="errorQuantity"></div>
JS :
$('#button-cart').on('click', function()
{
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
var val = $(this).val() || 0;
if(val != 0) {
val = val.replace('.', '');
val = val.replace(',', '.');
val = parseFloat(val);
}
console.log(val);
sum += val;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").html("You have select greater than 7: meal count: " + sum).show();
}
});
This work, but i want to validate form before submit.
If the sum < 7, do not submit.
How can i do it ?
Thanks!