Home / Admin / How to Use Conditional Logic With a Date Picker
Duplicate Snippet

Embed Snippet on Your Site

How to Use Conditional Logic With a Date Picker

<10
Code Preview
php
<?php
/**
 * Use conditional logic with a date field to show or hide another form field
 *
 * @link  https://wpforms.com/developers/how-to-use-conditional-logic-with-a-date-picker/
 */
  
add_action( 'wp_head', function () { ?>
   
    <style>
  
    /* CSS hide this field on page load */
    #wpforms-form-2575 .age-restriction {
            display:none;
        }
     
    /* CSS show this field if date conditional logic is true */
    #wpforms-form-2575 .age-restriction.show-field {
            display:block;
        }
   
    </style>
   
<?php } );
 
 
// Conditional logic for a field
function wpf_dev_age_restriction_check() {
    ?>
    <script>
        jQuery(function($) {
              
            // Only fire this script when the field ID 22 for form ID 2575 is changed
            document.querySelector( "#wpforms-2575-field_22-container" ).onchange = function() { 
              
                // Get year selected from Date Of Birth field for 
                // form ID 2575 and 
                // field ID 22
                var oneDate = $( "input#wpforms-2575-field_22" ).val();
                var date_selected = new Date(oneDate); 
                var date_selected_formatted = date_selected.toLocaleDateString();
                var year_selected = date_selected.getYear();
                 
                // Get current year
                var twoDate = new Date();
                var now = twoDate.toLocaleDateString();
                var year_now = twoDate.getYear();
                  
                // Is person 21 years or older? 
                if ((year_now - year_selected) < 21) {
                     
                    // No, then we will continue to hide the single line text field
                    $( ".age-restriction" ).addClass( "no" );
                    } 
                    else {
                    // Yes, then we will show the single line text field            
                    $( ".age-restriction" ).addClass( "show-field" );
                    }
 
            }
             
        });
          
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_age_restriction_check', 10 );

Comments

Add a Comment