Reputation: 27384
I have a form that I validate with jQuery Validate. I want to be able to disable the submit button when the form is invalid but I am unsure of the best approach. To disable the button I can simply do this
$("#clientConfigurationForm input[type=submit]")
.prop("disabled", !clientConfigValidation.valid());
The issue is where do I put this code? It seems that the only way to track all changes is to replicate the code in both unhighlight
and highlight
.
Is there a better way to approach this issue?
Upvotes: 3
Views: 6597
Reputation: 98738
Quote OP's Comment:
"This doesnt entirely work, because if I enable and disable a checkbox then the form inputs disable and then become enabled again, at this point clientConfigValidation.valid() says true but, on submit, it realises its not actually valid... Very odd"
This is caused by a timing issue regarding when the value of the checkbox actually changes.
To fix it change your change
event into a click
event to more immediately capture your checkbox and radio buttons. This does not seem to alter how the rest of the input elements behave, because you have to click
on them when you change
them.
$('input, select, textarea').on('click', checkForm);
function checkForm(){
$("input[type=submit]")
.prop("disabled", !($('#clientConfigurationForm').valid()));
}
Working DEMO: http://jsfiddle.net/8umJ6/
If you notice any issues with one input type over another, you could tweak the code by specifying different events for different input types.
$('input[type="checkbox"], input[type="radio"]').on('click', checkForm);
$('input[type="text"], select, textarea').on('change', checkForm);
function checkForm(){
$('input[type="submit"]')
.prop("disabled", !($('#clientConfigurationForm').valid()));
}
Upvotes: 1
Reputation: 2988
I'd execute it when an input is changed.
$('#yourForm input, #yourForm select, #yourForm textarea').on('change', checkForm);
function checkForm(){
$("#clientConfigurationForm input[type=submit]")
.prop("disabled", !clientConfigValidation.valid());
}
Upvotes: 2