The answer to the above question helped me, but I still have a problem: Show hide custom Woocommerce checkout field based on selected payment method
I want the Phone field (a field is required) to be displayed when the customer selects the cheque payment gateway, and the mobile field is not displayed and disabled if he selects other payment gateways.
// 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_phone_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 "cheque"
if( $(b).val() !== 'cheque' )
showHide( c, 'hide' );
else
showHide( c );
// Live event (When payment method is changed): Show or Hide based on "cheque"
$( 'form.checkout' ).on( 'change', a, function() {
if( $(b).val() !== 'cheque' )
showHide( c, 'hide' );
else
showHide( c );
});
});
</script>
<?php
endif;
}
The problem is when I choose other payment gateways besides cheque, even though the Phone field is hidden, it is still validated and displays the error (Billing Phone is a required field) – and this field needs to be filled, I don’t want this!
2
Answers
You can use jquery
.prop('disabled', true);
and.prop('disabled', false);
to the input selector. Try below code.To remove
(Billing Phone is a required field)!
when the payment gateway is not cheque then You can usewoocommerce_checkout_fields
hook.The following will do the job, adding a hidden field to handle the billing phone validation when the billing phone field is visible. When the billing phone field is hidden and empty, no validation error will be prompted, allowing placing the order silently:
Code goes in functions.php file of your active child theme (or in a plugin). Tested and works.