Removing/Adding Requirement from fields

superdmon 13 Sep, 2016
Hello,

I have a form that asks the user if they would like to be contacted as a follow up via a drop down menu. If they answer yes (which is default), this leaves the field required but should they not wish to be and they select "No", it removes the requirement from the fields.

The jQuery I created works at removing the requirement, however, when I try to switch back to "Yes", the field's requirement class is added back but can still be submitted without the fields having been entered.

Here's my code:

<script>


    jQuery('#contact_you').change(function(){
        if(this.value == "Yes") {

                       jQuery('#name').html('<input class="validate['required'] gvalidate_valid" id="your_name" name="your_name" type="text" value="">');
                       jQuery('#phone').html('<input class="validate['required'] gvalidate_valid" id="your_phone" name="your_phone" type="text" value="">');
                       jQuery('span.check_first').addClass("required").removeClass("hidden");

        } else {
                       jQuery('#name').html('<input class="" id="your_name" name="your_name" type="text" value="">');
                       jQuery('#phone').html('<input class="" id="your_phone" name="your_phone" type="text" value="">');
                       jQuery('span.check_first').removeClass("required").addClass("hidden");

    }

});

</script>


I'm not sure what's at play here, can anyone offer any suggestions?
GreyHead 14 Sep, 2016
Hi superdmon,

This is a ChronoForms weakness, the validation is set up when the form loads, and adding or removing classes after then doesn't seem to change the validation :-(

I have got round this in the past by using the jQuery validate plug-in instead of the CF validation as that has much more fine-grained controls.

I guess that you could also get round it by having two identical inputs (but with different ids) one required and one not and then swap over the display with JavaScript. I think that would work.

Bob
superdmon 15 Sep, 2016
Thanks for your response GreyHead.

I had thought of the two input field option before but wanted to avoid that option unless it came to it. I think I will try and use this option but I may look into using the jQuery validate instead.
This topic is locked and no more replies can be posted.

VPS & Email Hosting 20% discount
hostinger