-->

WooCommerce: trigger event after change of variati

2019-01-13 09:14发布

问题:

We use Woocommerce to sell colorboxes. Mostly the variable-product option is chosen.

We added a modal dialog with a color palette, where the customer can chose a color from. This is next to the common dropdown of woocommerce.

Problem is, when I pass the right SlugValue to the dropdown (after it gets chosen from palette) then the value in the dropdown is correct, but the event that need to be fired to publish the price doens't works.

I already tried to fire the onchange event of the dropdown, but nothing happend.

Can anybody tell me, which event needs to be triggered, and how?

aprec any help!

回答1:

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.



回答2:

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.