I have added a custom select field and a custom text field on the checkout page in WooCommerce using the code below.
I want to hide this text field by default and it should only be visible when the "Referral Program" option is selected from the select field
Here is my code, which works. Except that the textfield is always visible, whatever choice is made.
// add fields
add_action( 'woocommerce_after_checkout_billing_form', 'my_select_field' );
add_action( 'woocommerce_after_order_notes', 'referralName_textbox' );
// save fields to order meta
add_action( 'woocommerce_checkout_update_order_meta', 'save_what_we_added' );
// select
function my_select_field( $checkout ){
// you can also add some custom HTML here
woocommerce_form_field( 'referrence', array(
'type' => 'select', // text, textarea, select, radio, checkbox, password, about custom validation a little later
'required' => true,
'class' => array('my-field', 'form-row-wide'), // array only, read more about classes and styling in the previous step
'label' => 'From where you hear about us',
'label_class' => 'my-label',
'options' => array( // options for <select> or <input type="radio" />
'' => 'Please select', // empty values means that field is not selected
'Google' => 'Google', // 'value'=>'Name'
'LinkedIn' => 'LinkedIn',
'Facebook' => 'Facebook',
'Email' => 'Email',
'Referral Program' => 'Referral Program', // 'value'=>'Name'
'Other' => 'Other'
)
), $checkout->get_value( 'referrence' ) );
// you can also add some custom HTML here
}
// checkbox
function referralName_textbox( $checkout ) {
woocommerce_form_field( 'referralName', array(
'type' => 'text',
'class' => array('my-field form-row-wide'),
'label' => ' Referral Name',
), $checkout->get_value( 'Referral Name' ) );
}
// save field values
function misha_save_what_we_added( $order_id ){
if( !empty( $_POST['referrence'] ) )
update_post_meta( $order_id, 'referrence', sanitize_text_field( $_POST['referrence'] ) );
if( !empty( $_POST['ReferralName'] ) )
update_post_meta( $order_id, 'ReferralName', sanitize_text_field( $_POST['ReferralName'] ));
}
//
Can you please guide me on how to achieve the text field is only visible, depending on the choice in the select field using WordPress hooks and functions?