Kimmo
Kimmo

Reputation: 67

Woocommerce radio button check on jquery

I have a custom shipping method on WooCommerce that should show a little box with information to user, only when that custom shipping method is chosen.

So far I have tried with this little code:

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

And it shows the .custom-box just fine when that custom shipping method is chosen. But it does not hide it for some reason, when I choose some other shipping method?

Also it does not show the box if my custom shipping method is chosen on page load, but if I click on some other shipping method, and then my custom shipping method, it will show the box fine.

Working now perfectly. Thanks for the working solution for Томица Кораћ at below!

Upvotes: 1

Views: 1832

Answers (1)

Томица Кораћ
Томица Кораћ

Reputation: 2672

Try this script:

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

Let me know if this works for you.

Edit

I've updated the script. Please try this and let me know if it works:

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

Upvotes: 2

Related Questions