Search code examples
jquerydatepickergravity-forms-plugin

How To Reinitialize datepicker with new filter in Gravity Forms


I am using a gravity form data picker and need to disable a date range based on the select field at the top of the form if the value equals "Framingham". I'm pretty sure that I need to destroy the datepicker and reinitialize it on change, but I'm not entirely sure. If "Framingham" is not selected then the 45 days should be 30 instead. This is as far as I could get:

jQuery(function(){
        jQuery('#input_3_23').on('change', function(){
            if(jQuery(this).val() == 'Framingham'){

                for(var i=0; i<45; i++){ 
                      var day=new Date(year, month, date + i);
                      disabledDays.push(("0" + (day.getMonth() + 1)).slice(-2) + '/' + ("0" + day.getDate()).slice(-2) + '/' +  day.getFullYear()   );
                }

                gform.addFilter( 'gform_datepicker_options_pre_init', function( optionsObj, formId, fieldId ) {
                    if (formId == 3 && fieldId == 14 || formId == 3 && fieldId == 15 || formId == 3 && fieldId == 16) {
                        optionsObj.minDate = 0;

                        optionsObj.beforeShowDay = function(date) {
                            var checkdate = jQuery.datepicker.formatDate('mm/dd/yy', date);
                            return [disabledDays.indexOf(checkdate) == -1];
                        };
                    }
                return optionsObj;

                });
            }
        });
    });

I also have a user selectable disableDays array which is where the

return [disabledDays.indexOf(checkdate) == -1];

is coming from. Any help would be super appreciated!


Solution

  • A less elegant but simpler solution might be to add two Date fields to your form. One with the 45 day cap and the other with the 30 day cap. Then you can use Gravity Forms' conditional logic to show/hide the corresponding Date field based on the value selected in your Drop Down field.

    If you go this route, you might also be interested in GP Limit Dates which would allow you to limit the date ranges without any custom code.