The following article will present step by step how one can retrieve in javascript the selected simple produit id at configurable options’ selection in Magento2.

Step 1: Override configurable template
   First we’ll need to override the default configurable template from our custom theme.
So create the file MyVendorName/MyTheme/Magento_ConfigurableProduct/templates/product/view/type/options/configurable.phtml.
Then copy-paste the content of the core .phtml into the new file.

Step 2: Set up a javascript observer to get the product id at options selections.

<script>
require([
    'jquery',
    'Magento_Ui/js/modal/modal'
  ],
  function(jQuery) {
    jQuery(function () {
      jQuery(".product-options-wrapper select[id^='attribute']").on("change", function () {
        setTimeout(function () {
          var selectsValues = jQuery(".product-options-wrapper select[id^='attribute']");
          if (selectsValues[0].value !== "" && selectsValues[1].value !== "") {
            var configurable = jQuery("#product_addtocart_form").data('mageConfigurable');
            var selectedProductId = configurable.simpleProduct;
            console.log('Selected simple product Id is: ', selectedProductId);
          }
        }, 500);
      });
    });
  }
})
</script>

The code is self explanatory, but in brief, here’s what’s happening.
First we watch the select element waiting the user input.
At select option change we check to see if all attributes have been selected.
In this sample, let’s suppose we have two configurable options size and color.
Which means that we will only be checking the first two indexes of the select array element

selectsValues[1]

selectsValues[1]

.

This can be adapted to your need. Once we’re sure that every required options have been selected, we then proceed to get the magento2 widget handling configurable product display (jQuery("#product_addtocart_form").data('mageConfigurable')).
At last we can just access the simpleProduct variable which will contain the selected product id.

Leave a comment