WooCommerce: trigger event after change of variation

戏子无情 提交于 2019-11-27 17:54:20

In case anyone stumbles across this in the future: WooCommerce provides triggers throughout the add-to-cart-variation.js which allows you to hook into change events for the website. You can find all of them available in that file, but one which will likely help most in this case can be used as such

$( ".variations_form" ).on( "woocommerce_variation_select_change", function () {
    // Fires whenever variation selects are changed
} );

$( ".single_variation_wrap" ).on( "show_variation", function ( event, variation ) {
    // Fired when the user selects all the required dropdowns / attributes
    // and a final variation is selected / shown
} );

Where the trigger you want to hook into is the first argument inside .on(). Here's a few below to get you started:

woocommerce_variation_select_change Fires when the select is changed.

show_variation is fired when it finds a variation, and will actually pass you the variation object that is found so you can get direct access to the price without having to filter through the selects manually.

You can sift through and find the rest here.

This code performs the exact functionality requested in the initial question:

$('#WC_variation_drop_down_ID').trigger('change');

Change '#WC_variation_drop_down_ID' to the actual ID of the field you changed with jQuery.

Here is a more complete solution that includes setting the field as well as triggering the WooCommerce variation selection (based on array of radio button field classes):

var fields = ['.gchoice_4_11_0', '.gchoice_4_11_1', '.gchoice_4_4_0', '.gchoice_4_4_1'];
for ( var i = fields.length; i--; ) {
    $('#gravity_form_wrapper_ID').on('click', fields[i], function() {
        $('#WC_variation_drop_down_ID').val( $(this).children('input').val() ).trigger('change');
    });
}

Solution inspired by this post on setting WooCommerce Variation Fields.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!