0

I want to put a checkbox before all fields where I want to ask people if they have vat number and when they check that checkbox I want to display vat_number field, also when isn't checked I want to hide that field. I found a code on internet, but doesn't work. Please take a look on my picture to understand. Thanks in advance, I will really appreciate!

enter image description here

1
  • can you please update your code here so I can help you. Commented Aug 25, 2021 at 5:29

1 Answer 1

0

Put this code in functions.php file.

add_filter( 'woocommerce_checkout_fields' , 'rws_display_checkbox_and_new_checkout_field' ); 
function rws_display_checkbox_and_new_checkout_field( $fields ) {
$fields['billing']['have_vat_number'] = array(
    'type'      => 'checkbox',
    'label'     => __('Are you have Vat Number?', 'woocommerce'),
    'class'     => array('form-row-wide'),
    'clear'     => true
);   
$fields['billing']['vat_number'] = array(
    'label'     => __('Vat Number', 'woocommerce'),
    'placeholder'   => _x('Vat Number', 'placeholder', 'woocommerce'),
    'class'     => array('form-row-wide'),
    'clear'     => true
);
return $fields;
}
add_action( 'woocommerce_after_checkout_form', 'rws_conditionally_hide_show_new_field', 9999 );
function rws_conditionally_hide_show_new_field() {
  wc_enqueue_js( "
      jQuery('input#have_vat_number').change(function(){
         if (! this.checked) {
            jQuery('#vat_number_field').fadeOut();
            jQuery('#vat_number_field input').val('');         
         } else {
            jQuery('#vat_number_field').fadeIn();
         } 
      }).change();
  ");   
}
function rws_move_checkout_email_field( $address_fields ) {
    $address_fields['have_vat_number']['priority'] = 1;
    $address_fields['vat_number']['priority'] = 21;
    return $address_fields;
}
add_filter( 'woocommerce_billing_fields', 'rws_move_checkout_email_field', 10 , 1 );
1
  • Thank you so much, I appreciate!
    – user208374
    Commented Aug 25, 2021 at 12:14