Boris Callens
Boris Callens

Reputation: 93297

Disable/enable entire form's submit with jquery

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?

Upvotes: 7

Views: 47428

Answers (7)

Philip Mc lennan
Philip Mc lennan

Reputation: 33

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

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

Upvotes: 1

karim79
karim79

Reputation: 342625

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.

Upvotes: 1

theoski
theoski

Reputation: 109

Just a simplification of Nick's original answer:

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

Upvotes: 2

Nicholas Franceschina
Nicholas Franceschina

Reputation: 6147

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


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

Upvotes: 13

Hawk Kroeger
Hawk Kroeger

Reputation: 2334

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();
   }
}

Upvotes: 0

Alexander Taubenkorb
Alexander Taubenkorb

Reputation: 3279

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');
}

Upvotes: 10

Pim Jager
Pim Jager

Reputation: 32119

How about doing the check inside the submit method:

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

Upvotes: 7

Related Questions