Disable submit button when form is invalid

◇◆丶佛笑我妖孽 提交于 2020-01-02 18:16:10

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/18848325/disable-submit-button-when-form-is-invalid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!