Dynamically show and make custom Woocommerce checkout field required after another custom field (checkbox) is checked

Viewed 928

I am searching for a while now to achieve what I am describing to my title.

This is the code I am using right now to my child theme's functions.php file:

//--------------------add custom fields to billing section--------------------------------------------
add_filter( 'woocommerce_checkout_fields' , 'display_checkbox_and_new_checkout_field', 20 );
  
function display_checkbox_and_new_checkout_field( $fields ) {
  
$fields['billing']['checkbox_trigger'] = array(
    'type'      => 'checkbox',
    'label'     => __('Επιθυμώ Τιμολόγιο', 'woocommerce'),
    'class'     => array('form-row-wide'),
    'clear'     => true
);   
    
$fields['billing']['afm_field'] = array(
    'label'     => __('ΑΦΜ Εταιρείας', 'woocommerce'),
    'placeholder'   => _x('καταχωρείστε το ΑΦΜ σας...', 'placeholder', 'woocommerce'),
    //'required' => true,
    'class'     => array('form-row-wide'),
    'clear'     => true
);
  
return $fields;
  
}


//toggle feature for the custom field that I need to make required after checkbox is clicked

add_action( 'woocommerce_after_checkout_form', 'conditionally_hide_show_new_field', 9999 );
  
function conditionally_hide_show_new_field() {
    
  wc_enqueue_js( "
      jQuery('input#checkbox_trigger').change(function(){
           
         if (! this.checked) {
            // HIDE IF NOT CHECKED
            jQuery('#afm_field_field').hide();
            jQuery('#afm_field_field').removeClass('validate-required');
         } else {
            // SHOW IF CHECKED
            jQuery('#afm_field_field').show();
            jQuery('#afm_field_field').addClass('validate-required');
         }
           
      }).change();
  ");
       
}

I have already tried the following also but it seems to not working:

add_filter( 'woocommerce_checkout_process' , 'if_checked_make_afm_required', 20 );
  
function if_checked_make_afm_required() {
    
    $step = WC()->session->get( 'post_data' );
    
    if ( isset($step['checkbox_trigger']) ) {
        $fields['billing']['afm_field']['required'] = true;
    } else {
        $fields['billing']['afm_field']['required'] = false;
    }
  
}

I would really appreciate it if anyone could help here. Thanks in advance!

0 Answers
Related