Reputation: 1271
I have the very simple code below that installs an event handler on confirmPass keystrokes. On registration form submit I want to be able to disable the submit if the passwords do not match. In the 'onClick' event for the registration form if I call confirmPass() it fails to submit, if I comment it out it submits. Why is confirmPass() blocking the programatic form submit?
$( document ).ready(function() {
console.log( "ready!" );
$('#confirmPassword').keyup(function(){
confirmPass();
})
});
function registrationSubmit(){
confirmPass();
$('#registration').submit();
}
function confirmPass() {
var pass = $('#password').val();
var cpass = $('#confirmPassword').val();
if (!(pass == cpass)) {
$('#confirmPassword').addClass('text-danger');
$('#cpassmsg').addClass('text-danger').removeClass('ui-helper-hidden');
$('#cpassmsg').text("Confirm Password Fails")
$('#registration').submit(function (event) {
event.preventDefault();
});
return;
} else {
$('#confirmPassword').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').text("Confirm Password Match!")
}
Upvotes: 0
Views: 36
Reputation: 2851
this line adds an event handler.
$('#registration').submit(function (event) {
event.preventDefault();
});
Which means every time the submit event is fired after this line have been hit it will be cancelled. Since you call confirmPass
on each keystroke the line will be executed at least once and thus submits events on the form will always be cancelled. Instead you might want to only call submit only if the validations are succesfull and remove the line I mentionned above
Exemple
function registrationSubmit(event){
// Assuming you modify confirmPass to return true/false
if(confirmPass()){
$('#registration').submit();
}
}
Upvotes: 1
Reputation: 780852
You never remove the submit handlers that call preventDefault()
.
Instead of adding a handler in confirmPass()
, check whether the password is valid in registrationSubmit()
. Have confirmPass()
return a boolean to indicate this.
$(document).ready(function() {
console.log("ready!");
$('#confirmPassword').keyup(function() {
confirmPass();
})
});
function registrationSubmit() {
if (confirmPass())
$('#registration').submit();
}
}
function confirmPass() {
var pass = $('#password').val();
var cpass = $('#confirmPassword').val();
if (pass != cpass) {
$('#confirmPassword').addClass('text-danger');
$('#cpassmsg').addClass('text-danger').removeClass('ui-helper-hidden');
$('#cpassmsg').text("Confirm Password Fails")
return false;
} else {
$('#confirmPassword').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').text("Confirm Password Match!");
return true;
}
}
Upvotes: 1