7

When my form doesn't validate, I want to disable the form's submit function. I can do this by disabling the submit button, but this would leave the enter key unchecked.
I can set the .submit(return false); but then I can't re-enable it again later.

Any suggestions?

7 Answers 7

14

just a simplification of Pim's (edited to pull up James contribution):


$('#form').submit(formValidated);
Sign up to request clarification or add additional context in comments.

Comments

12

I did the following, which worked (disable submit button and form submit):

var condition = true; //check whatever you like
if(condition)
    $('input[type=submit]', this).attr('disabled', 'disabled');
    $('form').bind('submit',function(e){e.preventDefault();});
}else{
    $('input[type=submit]', this).removeAttr('disabled', 'disabled');
    $('form').unbind('submit');
}

Comments

7

How about doing the check inside the submit method:

$('#form').submit (function() {
 if(formValidated())
  return true;
 return false;
});

1 Comment

Just a note you probably already knew about: Don't forget to also make your validations on the server-side though because having javascript disabled will bypass this.
2

Just a simplification of Nick's original answer:

$('#form').submit(formValidated);

Comments

1

Here's another possible solution:

$('#form').change(function() {
    (isValid($('#form')) ? $('#submitBtn').attr('disabled',false) : $('#submitBtn').attr('disabled',true)
});

Of course, isValid() checks that all your $('#form') elements comply to your validation rules. That's how I would do it.

Comments

1

This is the only piece of code that works for me.

$('#form').submit(function(e) {
    e.preventDefault();
    // or return false;
}); 

2 Comments

Try to elaborate a bit more and explain why it works, but good job! :)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

Instead of directly calling the submit function call an intermediary function and do a check in there.

i.e.

var isSubmitable = false;

function submitForm() {
   if(isSubmitable) {
       myform.submit();
   }
}

Comments

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.