Wooccommerce单选按钮检查jquery

Woocommerce radio button check on jquery

本文关键字:jquery 检查 单选按钮 Wooccommerce      更新时间:2023-09-26

我在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框。但它并没有因为某种原因而隐藏它,当我选择其他运输方式时?

此外,如果在页面加载时选择了我的自定义运输方法,它不会显示框,但如果我单击其他运输方法,然后单击我的自定义运送方法,它会显示框。

现在工作得很好。感谢以下ТомицаКора的工作解决方案!

试试这个脚本:

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);
});