Search code examples
jqueryjquery-validatedisabled-input

Enable form select validation after re-enabling it with jQuery validation


Using jQuery Validation. How can I make sure jQuery validates an input that was initially disabled, but then re-enabled based on other form input?

This seems like it would be somewhat common, but I can't seem to track down an answer. I have an initial form that contains a disabled select dropdown. Once the user enters some other information in the form, the select dropdown is enabled. When I submit the form, it doesn't seem to be validating the "required" select dropdown that was initially disabled.

Thanks.


Solution

  • Jquery validation plugin will do that automatically. Check the following example:

    $(document).ready(function() {
    
        $('#myform').validate({
            rules: {
                foo: {
                    required: true
                },
                bar: {
                    required: true
                }
            }
        });
        
        $('#enable').click(function(){
        	$('#bar').attr('disabled', false);
        });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
    
    <form id="myform">
        <input type="text" name="foo" />
        <br>
        <input type="text" name="bar" id="bar" disabled />
        <br>
        <a href="javascript:void(0);" id="enable">Enable It</a>
        <br>
        <input type="submit" />
    </form>