Php 使用ajax修改必填字段

Php 使用ajax修改必填字段,php,ajax,wordpress,woocommerce,Php,Ajax,Wordpress,Woocommerce,我根据需要在子主题的function.php中添加了Woocommerce账单地址a字段,如“field_x”。然后在同一页面中添加了带有两个选项“a和B”的单选按钮。我想这样做: 如果用户选择单选选项A,“我的自定义字段”将不可见且“非必需” 如果用户选择单选选项B,我的自定义字段将可见且为“必需” 我的示例代码: <? // Adding fields and radios add_filter('woocommerce_billing_fields', 'some_woocommer

我根据需要在子主题的function.php中添加了Woocommerce账单地址a字段,如“field_x”。然后在同一页面中添加了带有两个选项“a和B”的单选按钮。我想这样做:

如果用户选择单选选项A,“我的自定义字段”将不可见且“非必需” 如果用户选择单选选项B,我的自定义字段将可见且为“必需”

我的示例代码:

<?
// Adding fields and radios
add_filter('woocommerce_billing_fields', 'some_woocommerce_billing_fields', 10, 1);

function some_woocommerce_billing_fields($fields) {
    $fields['radio_select'] = array(
            'label' => __('Please select', 'woocommerce'),
            'required' => true,
            'clear' => false,
            'type' => 'radio',
            'options' => array(
                'op_a' => __('op A', 'woocommerce'),
                'op_b' => __('op B', 'woocommerce')));
    $fields['field_x'] = array(
            'label' => __('Field X', 'woocommerce'),
            'placeholder' => _x('Field X', 'placeholder', 'woocommerce'),
            'required' => true,
            'clear' => false);

    return $fields;
}

// PHP functions for Ajax calls
add_action('wp_enqueue_scripts', 'majax_enqueue_scripts');
add_action('wp_ajax_f_remove_req', 'f_remove_req');
add_action('wp_ajax_nopriv_f_remove_req', 'f_remove_req');

function majax_enqueue_scripts() {
    $nonce = wp_create_nonce("nonce_t");
    wp_enqueue_script('url', true);
    wp_localize_script('url', 'urlm', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => $nonce));
}
// Adding filter to remove require
function f_remove_req() {
    if (!wp_verify_nonce($_POST['nonce'], 'nonce_t'))
        die();
    add_filter('woocommerce_process_myaccount_field_field_x', 'remove_reqs', 10, 1);
    die();
}
// Removing require
function remove_reqs($field) {
    $field['field_x']['required'] = false;
    return $field;
}

// Add Ajax function
add_action('woocommerce_after_edit_account_address_form', 'address_script');

function address_script() {
     ?>
     < script >
    jQuery(document).ready(function () {
        jQuery('#radio_select_op_a').change(function () {
            jQuery('#field_x_field').hide();

            jQuery.post(urlm.ajax_url, {
                'action' : 'f_remove_req',
                'nonce' : urlm.nonce
            },
                function (response) {
                console.log(response);
            });
        });
        jQuery('#radio_select_op_b').change(function () {
            jQuery('#field_x_field').show();

            jQuery.post(urlm.ajax_url, {
                'action' : 'f_add_req',
                'nonce' : urlm.nonce
            },
                function (response) {
                console.log(response);
            });
        });
    });
     </ script>
     <?
}
?>