Magento 2 Configurable Product – Set Option via JavaScript

configurable-productjavascriptmagento2

I would like to automatically set a configurable product option.

I tried to do it via javascript:

<script>
    require(["jquery", "jquery/ui"], function ($) {
        $(document).ready(function(){
            $('#attribute93').val(12).change();
        });
    });
</script>

The hardcoded id and value are for testing purposes only (both do exist).
The problem seems to be that the ready function is called before the dropdown select is completely rendered and ready for user interaction. $('#attribute93').val(12).change(); does work when triggered by a user's click.

Is there a way to tell when everything on a page is completely rendered? I found the afterRender event but that seems to relate to knockout js only.

Thank you

Best Answer

I found the perfect solution:

  1. Override configurable.js from Magento_Configurable module. Explained here: Magento2 - How to extend jQuery widget (configurable.js)

  2. override function _onGalleryLoaded()

    define(['jquery', 'jquery/ui', 'Magento_ConfigurableProduct/js/configurable'], function($){
    $.widget('om.configurable', $.mage.configurable, {
         _onGalleryLoaded: function (element) {
            var galleryObject = element.data('gallery');
            this.options.mediaGalleryInitial = galleryObject.returnCurrentImages();
    
            $('#attribute93').val(13).change();
        },
    });
    
    return $.om.configurable;
    

    });

Works like a charm.