Rushil
Rushil

Reputation: 135

Intercept a click on submit button and check validity of form jQuery

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

Answers (1)

Niemand
Niemand

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

Related Questions