Reputation: 135
I want to check validity of form on clicking the submit button. In case it is valid the form should submit otherwise do nothing. I've tried disabling the submit button and on click checking validity and enabling it. But I see two issues with this approach. 1: Clicks are not detected on a disabled button 2: Even if I manage to get a click detected, I'll probably end up in an infinite loop. The second click after the button is enabled will again trigger the validity check and so in.
Upvotes: 4
Views: 9353
Reputation: 346
You should use event.preventDefault()
. Read this: http://api.jquery.com/event.preventDefault/
Rough sample code draft:
$('your-submit-button').click(function(event){
if (! validate() ) {
event.preventDefault();
showErrors();
}
})
Where validate()
is your validation function, returning false in case of validation fail.
Edit:
Sample handler is bind to click
event, because you want
to check validity of form on clicking the submit button
It's better practice to use .submit()
instead of .click()
, for validation to be made for any type of form submitting.
Our sample stays almost unchanged:
$('#your-form-id').submit(function(event){
if (! validate() ) {
event.preventDefault();
showErrors();
}
})
Upvotes: 6