Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lkraav/6558e260480925ff419d79360d9468e5 to your computer and use it in GitHub Desktop.
Save lkraav/6558e260480925ff419d79360d9468e5 to your computer and use it in GitHub Desktop.
<script>
(function( $, window, document, undefined ) {
/**
* `VariationForm.update_variation_values` can only differentiate
* variations by `value` attributes. Our secondary dimension is
* `data-variation-id`. Memoize original selection here.
*
* @see {@link https://github.com/woocommerce/woocommerce/blob/2.6.14/assets/js/frontend/add-to-cart-variation.js}
* @see {@link https://github.com/woocommerce/woocommerce/issues/12929}
* @type {number}
*/
var optionVariationId = null;
$( ".variations_form" )
.on( "woocommerce_variation_select_change", function( event ) {
optionVariationId = $( this ).find( "select option:selected" ).data( "variation-id" );
} )
/**
* `value` attributes may be identical, modify `selected` directly.
*
* @see {@link https://stackoverflow.com/questions/1414276/how-to-make-the-first-option-of-select-selected-with-jquery}
*/
.on( "woocommerce_variation_has_changed", function( event ) {
if ( optionVariationId ) {
// Re-select original `<option>` element.
$( this ).find( "select option:selected" ).prop( "selected", false );
$( this ).find( "select option[data-variation-id=" + optionVariationId + "]").prop( "selected", "selected" );
// Update add to cart variation id.
$( this ).find( 'input[name="variation_id"]' ).val( optionVariationId ).change();
}
} );
}( jQuery, window, document ));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment