Woocommerce 单选按钮检查 jquery

Woocommerce radio button check on jquery

我在 WooCommerce 上有一个自定义送货方式,只有在选择该自定义送货方式时,它才会向用户显示一个包含信息的小框。

到目前为止,我已经尝试过这个小代码:

jQuery(document).ready(function($) {
    $(document).on("change", "#shipping_method_0_my_shipping_method", function() {
        if( $("#shipping_method_0_my_shipping_method").prop('checked') == true ){
            $('.custom-box').show();
        } else {
            $('.custom-box').hide();
        }
    });
});

并且在选择自定义送货方式时,它显示 .custom-box 就好了。但是当我选择其他运输方式时,出于某种原因它并没有隐藏它?

如果在页面加载时选择了我的自定义送货方式,它也不会显示盒子,但如果我点击其他送货方式,然后点击我的自定义送货方式,它会正常显示盒子。

现在工作完美。感谢您提供下方 Томица Кораћ 的工作解决方案!

试试这个脚本:

jQuery(document).ready(function($) {

    // Create reusable function to show or hide .custom-box
    function toggleCustomBox() {
        // Get id of selected input
        var selectedMethod = $('input:checked', '#shipping_method').attr('id');

        // Toggle .custom-box depending on the selected input's id
        // Replace 'shipping_method_0_my_shipping_method' with your desired id
        if (selectedMethod === 'shipping_method_0_my_shipping_method') {
            $('.custom-box').show();
        } else {
            $('.custom-box').hide();
        };
    };

    // Fire our function on page load
    $(document).ready(toggleCustomBox);

    // Fire our function on radio button change
    $('#shipping_method input:radio').change(toggleCustomBox);
});

让我知道这是否适合你。

编辑

我已经更新了脚本。请试试这个,让我知道它是否有效:

jQuery(document).ready(function($) {

    // Create reusable function to show or hide .custom-box
    function toggleCustomBox() {
        // Get id of selected input
        var selectedMethod = $('input:checked', '#shipping_method').attr('id');

        // Toggle .custom-box depending on the selected input's id
        // Replace 'shipping_method_0_my_shipping_method' with your desired id
        if (selectedMethod === 'shipping_method_0_my_shipping_method') {
            $('.custom-box').show();
        } else {
            $('.custom-box').hide();
        };
    };

    // Fire our function on page load
    $(document).ready(toggleCustomBox);

    // Fire our function on radio button change
    $(document).on('change', '#shipping_method input:radio', toggleCustomBox);
});