4

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.

1 Answer 1

6

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();
    }
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Worked perfectly :>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.