Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable submit button when form is invalid

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?

like image 516
Chris Avatar asked May 31 '26 00:05

Chris


2 Answers

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());
}
like image 195
Michael Kunst Avatar answered Jun 02 '26 03:06

Michael Kunst


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()));
}
like image 20
Sparky Avatar answered Jun 02 '26 03:06

Sparky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!