'Auto select first available options from a variation on WooCommerce variable products

I have a t-shirt product that has a choice of sizes and colours. After selecting of one variation I would like the first available option to be auto selected in the other variation.

For example, if I had a white t-shirt with only Large and Extra Large and a green t-shirt with only Small and Medium, when the user selects White it should auto select to Large. However, if the user then changes their mind and goes for Green, it should auto select to Small. Although, this should only occur if there isn't an already available option selected in the other variation.

Whilst I can run a script to select the first enabled option on change, once the user changes to a different colour again, WooCommerce gives an 'Out of stock' warning and clears their choices before I can run the script on change again.

I've attempted to run with on woocommerce_variation_select_change, woocommerce_variation_has_changed and show_variation hide_variation without any luck.

Any help would be much appreciated. Below is roughly what I've come up with so far:

$(document).on( 'change', '.variations select', function( event ) {
        
    if ( !$(this).val() ) return false;
    var select = $(this);
    var variations = $(this).closest('.variations');
    
    $(variations).find('select').not(select).each(function() {

        var val = $(this).val();
            
        if ( !val || ( val && !$(this).find('option[value='+val+']:enabled') ) ) {

            $(this).find('option:enabled').each(function() {
                            
                if ( $(this).attr('value') ) {
                        
                    $(this).prop('selected', 'selected');
                    return false;
    
                }

            });
        
        } 

    });
    
});


Solution 1:[1]

You can achieve the solution to this problem using functions.php instead of writing js on the client-side.

add_filter('woocommerce_dropdown_variation_attribute_options_args','fun_select_default_option',10,1);
function fun_select_default_option( $args)
{

    if(count($args['options']) > 0) //Check the count of available options in dropdown
        $args['selected'] = $args['options'][0];
    return $args;
}

note: The answer was copied from Wordpress StackExchange

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hasan Parasteh