Show hide custom Woocommerce checkout field based on selected payment method

The following code will hide billing_options custom optional checkout field when the selected payment method is Cash on delivery (“cod”):

// Conditional Show hide checkout fields based on chosen payment methods
add_action( 'wp_footer', 'conditionally_show_hide_billing_custom_field' );
function conditionally_show_hide_billing_custom_field(){
    // Only on checkout page
     if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script>
        jQuery(function($){
            var a="input[name="payment_method"]",
                b = a + ':checked',
                c="#billing_options_field"; // The checkout field <p> container selector

            // Function that shows or hide checkout fields
            function showHide( selector="", action = 'show' ){
                if( action == 'show' )
                    $(selector).show( 200, function(){
                        $(this).addClass("validate-required");
                    });
                else
                    $(selector).hide( 200, function(){
                        $(this).removeClass("validate-required");
                    });
                $(selector).removeClass("woocommerce-validated");
                $(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
            }

            // Initialising: Hide if choosen payment method is "cod"
            if( $(b).val() !== 'cod' )
                showHide( c, 'hide' );
            else
                showHide( c );

            // Live event (When payment method is changed): Show or Hide based on "cod"
            $( 'form.checkout' ).on( 'change', a, function() {
                if( $(b).val() !== 'cod' )
                    showHide( c, 'hide' );
                else
                    showHide( c );
            });
        });
    </script>
    <?php
    endif;
}

Code goes in function.php file of your active child theme (or active theme). tested and works.

Leave a Comment