Reputation: 93297
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
Reputation: 33
This is the only piece of code that works for me.
$('#form').submit(function(e) {
e.preventDefault();
// or return false;
});
Upvotes: 1
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
Reputation: 109
Just a simplification of Nick's original answer:
$('#form').submit(formValidated);
Upvotes: 2
Reputation: 6147
just a simplification of Pim's (edited to pull up James contribution):
$('#form').submit(formValidated);
Upvotes: 13
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
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
Reputation: 32119
How about doing the check inside the submit method:
$('#form').submit (function() {
if(formValidated())
return true;
return false;
});
Upvotes: 7