29

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.

The problem is that 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?

starball
  • 20,030
  • 7
  • 43
  • 238
MJay
  • 487
  • 1
  • 6
  • 13

5 Answers5

106

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.

Logan
  • 1,376
  • 1
  • 8
  • 10
  • 2
    I absolutely cannot get the 2nd event to fire for products with a single variation. The first one runs fine though. – Howdy_McGee Feb 19 '16 at 16:25
  • 1
    Hello, sorry to "re-open" this, but I'm having trouble listening to the very first event. Setup: there's a – koichirose Dec 12 '16 at 16:28
  • 2
    I would hook into the `wc_variation_form` event and try to do your select2 setup there. That should make sure that it's initialized and ready to go. I'm not sure if select2 continues to watch the original select to see if there are modifications made to it or not, so you *might* need to hook into `woocommerce_update_variation_values` and fire something that would update those values if they are not automatically. – Logan Dec 13 '16 at 12:11
  • 1
    Nice Solution, was not able to find this solution from hours. – Harish Kumar Mar 28 '18 at 12:40
  • 1
    Pointing in the right direction, but not a direct solution to the question asked. This code says which events are fired on manual select, but not how to fire them. – Adal May 14 '18 at 18:45
  • @Adal You're correct. Seems I misread a part of that when I wrote this answer a few years ago. I was searching for the answer to my question, and this result came up first and figured I would share. Sent an upvote your way! – Logan May 15 '18 at 19:47
  • To manually trigger the listener that changes the price shown, I found the correct event to dispatch on line 337 of "https://github.com/woocommerce/woocommerce/blob/master/assets/js/frontend/add-to-cart-variation.js". The event to dispatch is 'check_variations' & should be dispatched against the form – ceotoolsuite Oct 14 '20 at 20:54
  • This needs to be hooked after document ready, otherwise it won't work. – Aleksandar Mar 08 '22 at 15:07
  • How would I know which element fired it? Because with the first code, I get the old variation entry and not the new one... Thanks – Si8 Sep 24 '22 at 23:49
  • Is there a way to achieve this with vanilla JS? For instance using ```addEventListener()```? – Jeromy Adofo Aug 26 '23 at 16:55
8

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.

Adal
  • 606
  • 7
  • 12
2

If you want to know which variation has been selected.

You can look in the file: add-to-cart-variation.js and find that this function also gives you the variation data:

$( ".single_variation_wrap" ).on( "show_variation", function ( event, variation ) { }

And if you know your variation ID (you can find it by hoovering your variation in backend or by inspection this object when selecting your variation), then you can do:

$( ".single_variation_wrap" ).on( "show_variation", function ( event, variation ) { 
  if( variation.variation_id === your_variation_id ) {
    // Do stuff when this variation has been selected 
  }
});

I needed to show some additional information when one variation was selected, and this helped me. It is maybe a bit off topic, but this is the discussion I found when searching for this.

Mostly from this page

1

if anyone comes here like me to find the answer, I will provide a clarification in this.

We have a problem implementing the change function because we need to know the price of variation selected but 'woocommerce_variation_select_change' we got the price from previous variation.

So if you want to get the price of variation after change finish, you have to use 'woocommerce_variation_has_changed' jQuery function.

Example:

jQuery('#select_attribute_of_variation').on('woocommerce_variation_has_changed', function(){ // do your magic here... })

0

I also want a solution that my javascript is only working on 1st variation. The code is given below

add_action('admin_footer', 'script');
function script()
{
    ?>
    <script>
        jQuery(function ($) {
            jQuery('#woocommerce-product-data').on('woocommerce_variations_loaded', function () {
                jQuery(this).find('.woocommerce_variation').each(function () {
                    jQuery("#dp").keydown(function () {
                        var cost = document.getElementById("cost").value;
                        var dp = document.getElementById("dp").value;
                        console.log(dp);
                    });
                });
            });
        });

    </script>


    <?php

}
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/33084776) – Usitha Indeewara Nov 06 '22 at 11:46