Magento 2: Get Simple Product ID & Quantity in Configurable Product using Swatches

This article shows how you can get the associated Simple Product ID and Quantity (Qty) / inventory from a Configurable Product in frontend product detail page in Magento 2.x.

– The below code assumes that Swatches have been used in the product detail page.
– Suppose you have two configurable attributes (color and size) for your configurable product.
– When you click on any color swatch and then click on the size swatch:
– then the available stock quantity of that particular color & size associated product will be displayed.

You can add the below code Javascript and PHP at the beginning of this file: app/design/frontend/Theme_Namespace/Theme_Name/Magento_Catalog/ templates/product/view/addtocart.phtml.

Here’s the full code:


<script type="text/javascript">
requirejs(['jquery','underscore'], function(jQuery,_){
    jQuery(window).load(function(){
        jQuery( ".product-options-wrapper div" ).click(function() {
            selpro();
        });
    });
    function selpro () {
        var selected_options = {};
        jQuery('div.swatch-attribute').each(function(k,v){
            var attribute_id    = jQuery(v).attr('attribute-id');
            var option_selected = jQuery(v).attr('option-selected');
            //console.log(attribute_id, option_selected);
            if(!attribute_id || !option_selected){ return;}
            selected_options[attribute_id] = option_selected;
        });

        var product_id_index = jQuery('[data-role=swatch-options]').data('mageSwatchRenderer').options.jsonConfig.index;
        var found_ids = [];
        //console.log(product_id_index);
        jQuery.each(product_id_index, function(product_id,attributes){
            //console.log(product_id);
            var productIsSelected = function(attributes, selected_options){
                return _.isEqual(attributes, selected_options);
            }
            if(productIsSelected(attributes, selected_options)){
                found_ids.push(product_id);
            } 
        });
        
        //console.log(found_ids);

        if (found_ids.length) {
            var selected_product_id = found_ids[0];
            jQuery('.myli').css('display','none');
            jQuery('#div'+selected_product_id).toggle();
        }
    }
});
</script>    

<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product
    $productTypeInstance = $product->getTypeInstance();
    if ($product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
        $usedProducts = $productTypeInstance->getUsedProducts($product);
?>
        <ul>
            <?php foreach ($usedProducts  as $child) { ?>
                <li class="myli" id="div<?php echo $child->getId()?>" style="display:none;list-style:none">
                    <?php 
                    $productStockObj = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface')->getStockItem($child->getId());
                    echo "We have ".round($productStockObj->getData('qty'))." items in stock!";
                    ?>
                </li>
            <?php } ?>
        </ul> 
<?php 
    } else {
        $productStockObj = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface')->getStockItem($product->getId());
        echo "We have ".round($productStockObj->getData('qty'))." items in stock!";
    }
?>

References:

Magento 2 Get selected simple product id in configurable product
Show available inventory on configurable product magento 2
Magento 2: Extract Currently Selected Product ID or SKU