I know this is not a fresh question. I saw such as:
- Show or hide checkout fields based on shipping method in Woocommerce 3;
- Custom checkout field and shipping methods ajax interaction in Woocommerce 3;
But what I find, on checkout page event handlers are disabled on #shipping_method inputs. And I cant refresh billings checkout fields by .change() or .click() jQuery
. This was solved(see code).
And checkout fields on choosing method shipping also removed, and in array
WC()->checkout->get_checkout_fields()
they removed. But when I want to apply order, it notices me that fields, which I removed is required. May be I need to set this fields somewhere else?
My code now looks so:
<?php
add_action('wp_footer', 'checkout_refresh_fields');
function checkout_refresh_fields()
{
// Only checkout page
if (is_checkout() && !is_wc_endpoint_url()) :
?>
<script type="text/javascript">
jQuery(function($) {
var input = '#shipping_method input';
function checkInput(value) {
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'refresh_fields',
'input_val': value,
},
success: function(result) {
$('.main-form-checkout').find('.woocommerce-billing-fields').hide()
$('.main-form-checkout').append(result);
console.log(result);
}
});
}
$(input).each(function() {
console.log($(this).val());
if ($(this).val() === 'free_shipping:3' && $(this).is(':checked')) {
checkInput($(this).val());
}
})
$('.form.checkout').on('change', input, function() { --////Now this works
if(this.checked) {
checkInput($(this).val());
}
})
});
</script>
<?php
endif;
}
add_action('wp_ajax_refresh_fields', 'get_ajax_refresh_fields');
add_action('wp_ajax_nopriv_refresh_fields', 'get_ajax_refresh_fields');
function get_ajax_refresh_fields()
{
if (isset($_POST['input_val']) && $_POST['input_val'] === 'free_shipping:3') {
add_filter('woocommerce_checkout_fields', 'theme_remove_billing_checkout_fields');
function theme_remove_billing_checkout_fields($fields)
{
$fields['billing']['billing_address_1']['required'] = false;
unset($fields['billing']['billing_address_1']);
unset($fields['billing']['billing_address_2']);
return $fields;
}
}
WC()->checkout->checkout_form_billing();
wp_die();
}