I wrote a simple script for validating forms in jQuery.
These are the submit buttons:
<button type="submit" id="submitCrear" name="submitCrear">Confirm</button> ---->Cancel button
<button type="submit" value="cancelar" name="cancelar" id="btnCancelar">Cancel</button> ---->Confirm button
When the Cancel button is pressed, the form should be sent without making any validation. The opossite should happend with the Confirm button.
But this is what I don’t understand: when I press the Confirm button, the validation process starts normally, but then I press the Cancel button and the form is not send until all validations are complete(isValidForm variables becomes ‘true’).
<script type="text/javascript">
var isValidForm;
$(document).ready(function() {
$('#btnCancelar').click(function () {
$('form').submit();
});
$('#submitCrear').click(function () {
$('form').submit(function(){
return validarForm();
});
});
});
function validarForm(){
isValidForm = true;
$("input:text").each(function(i) {
if(this.value == ''){
if (!$("#errorMessage"+i).length > 0)
addErrorMessage(this, i, '*REQUERIDO');
isValidForm = false;
}else{
removeErrorMessage(this, i);
}
});
$("input:password").each(function(i) {
if(this.value == ''){
if (!$("#errorMessage"+(i+999)).length > 0)
addErrorMessage(this, (i+999), '*REQUERIDO');
isValidForm = false;
}else{
if(($(this).attr('id') == 'rePassword_r') && ($(this).val() != $("#password_r").val())){
if ($("#errorMessage"+(i+999)).length > 0){
removeErrorMessage(this, (i+999));
addErrorMessage(this, (i+999), 'The password doesn't match.');
}
isValidForm = false;
}else{
removeErrorMessage(this, (i+999));
}
}
});
return isValidForm;
}
function addErrorMessage(element, indice, mensaje){
...
}
function removeErrorMessage(element, indice){
...
}
</script>
What should I do in order to send the form with the Cancel button even when the validation process started?
Thanks in advance!
You have your two buttons and the following jQuery
The latter part of the jQuery means that when the form is submitted, it will be validated as you’ve assigned the validation to the form submittance, rather than the button click. Which is why it is now fired on both buttons.
By design, don’t buttons of type submit, submit the form regardless? So should you not just change your jQuery to be: