12

We have a configurable product on the front-end with two drop-downs (size and color)

How can I get the final simple product id once the user has made their selections

We have done this in Magento 1 but don't know how to do this in Magento 2. Any suggestion will be appreciated.

4
  • Specify where you want to this product Id? Jan 10, 2018 at 10:49
  • Hi Dhiren, I want this product ID on configurable product page. Want simple product ID after user selected all options. e.g. if there are 2 attributes are there size and color so if user select Small size and red color so we want ID of this simple product. Jan 11, 2018 at 5:57
  • Hi...did you find out any answer for this?
    – Rita Jose
    Feb 23, 2018 at 4:49
  • @RitaJose Please check answer added by me just now. Hope it will help you :) Feb 24, 2018 at 5:47

9 Answers 9

23

Got solution. I am writing answer of my question. Hope it will help others.



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 = [];
        jQuery.each(product_id_index, function(product_id,attributes){
            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);
    }
});


For Magento 2.4.0 version, change the below code from

var attribute_id    = jQuery(v).attr('attribute-id');
var option_selected = jQuery(v).attr('option-selected');

to

var attribute_id = jQuery(v).attr('data-attribute-id');
var option_selected = jQuery(v).attr('data-option-selected');
9
  • @sammer if it help you then you can accept my answer. Thank you :) May 31, 2018 at 6:42
  • Perfect! Thanks! Found similar code over here as well: alanstorm.com/magento-2-extract-currently-selected-product-id Jun 24, 2018 at 6:02
  • how can we get same on list page ?
    – OBAID
    Sep 28, 2018 at 12:54
  • How to get sku was able to get product_id Sep 24, 2019 at 7:25
  • Why is it not working on my side? It is giving me error here: jQuery('[data-role=swatch-options]').data('mageSwatchRenderer').options.jsonConfig.index; It says that it is undefined Jan 1, 2020 at 22:01
13

I write js code for get simple product id after selection. You can add following js Code in bottom of this file. app/design/frontend/[your_theme_package]/[your_theme]/Magento_ConfigurableProduct/templates/product/view/type/options/configurable.phtml

<script type="text/javascript">
require(["jquery"], function(jQuery) {
  jQuery(".product-options-wrapper select[id^='attribute']").last().on('change', function() {
      setTimeout(function (){
        simpleId=jQuery("input[name=selected_configurable_option]").val();
        alert(simpleId);
      }, 500); 
  }); }); </script>

Then clear cache, it works for me. See this screenshot:

enter image description here

2
  • This answer worked for me while the selected answer errors. The time delay is the critical step. I think some class variable names might have changed since the chosen answer was selected.
    – JustinP
    Mar 8, 2019 at 21:21
  • can we get custom attributes from it Aug 28, 2019 at 13:22
4

You can easily get child product ID from a jQuery widget instance, like this:

$('[data-role="swatch-options"]').data('mageSwatchRenderer').getProduct();

Just make sure to check if widget is initialized for an object, etc.

1
  • it is not working on the latest version of the Magento 2.
    – T P T
    Apr 11, 2023 at 7:04
2

Here I update the answer for Magento 2.4.4 change from this mageSwatchRenderer to mage-SwatchRenderer

also update whole code check below

var product_id_index = jQuery('[data-role=swatch-options]').data('mage-SwatchRenderer').options.jsonConfig.index;

 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('mage-SwatchRenderer').options.jsonConfig.index;
            var found_ids = [];
            jQuery.each(product_id_index, function(product_id,attributes){
                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);
        }
    });
1
  • 2
    yes this work for me for 2.4.4
    – Jay Parmar
    Jun 20, 2023 at 5:12
2

With the help of @Siddharth Nandava, I found that using $('[data-role=swatch-options]').data('mage-SwatchRenderer').getProduct(); , we can get ID of selected Swatch variation, we can also check it in console.

$( ".product-options-wrapper .swatch-opt" ).click(function() {
    selProId = ($('[data-role=swatch-options]').data('mage-SwatchRenderer').getProduct());
    console.log(selProId);
});

Note: To check in console, Don't forget add $=jQuery; on beginning of code or hit once in console when open console, or replace every $ with jQuery.

1

I did this to get the simple product Id.

created require-config.js app/code/Vendor/Test/view/frontend/requirejs-config.js

var config = { 
config: { 
mixins: {
 'Magento_Swatches/js/swatch-renderer': {
 'Vendor_Test/js/swatch-renderer-mixin': true 
    } 
  }
 } 
};

app/code/Vendor/Test/view/frontend/web/js/swatch-renderer-mixin.js

define(['jquery','configurableVariationQty'],function($,configurableVariationQty) 

{

    'use strict';

    return function (SwatchRenderer) {

        $.widget('mage.SwatchRenderer', SwatchRenderer, {
          
            _RenderControls: function () {
                this._super();

            },
            /** @inheritdoc */
            _OnClick: function ($this, widget) {
                console.log('variants are clicking....!!!!');
                console.log("ID clicked : " +widget.getProductId());

            }
        });
        return $.mage.SwatchRenderer; // Return flow of original action.
    };
});
1

Here I update the answer for Magento 2.4.5 change from this mageSwatchRenderer to mage-SwatchRenderer and for the attribute id

from

var attribute_id    = jQuery(v).attr('attribute-id');
var option_selected = jQuery(v).attr('option-selected');

to

var attribute_id    = jQuery(v).attr('data-attribute-id');
var option_selected = jQuery(v).attr('data-option-selected');

Here is whole code for your reference

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('data-attribute-id');
            var option_selected = jQuery(v).attr('data-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('mage-SwatchRenderer').options.jsonConfig.index;
        var found_ids = [];
        jQuery.each(product_id_index, function(product_id,attributes){
            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);
    }
});
0

For making it work in 2.4.2, from @vish's answer just change:

var attribute_id    = jQuery(v).attr('attribute-id');
var option_selected = jQuery(v).attr('option-selected');

to

let attribute_id    = jQuery(v).data('attribute-id');
let option_selected = jQuery(v).attr('data-option-selected');

as in the file swatch-renderer.js you can find the following snippet:

    /**
     * Get selected product list
     *
     * @returns {Array}
     * @private
     */
    _CalcProducts: function ($skipAttributeId) {
        var $widget = this,
            selectedOptions = '.' + $widget.options.classes.attributeClass + '[data-option-selected]',
            products = [];

        // Generate intersection of products
        $widget.element.find(selectedOptions).each(function () {
            var id = $(this).data('attribute-id'),
                option = $(this).attr('data-option-selected');

So by doing the change in line with vendor code, works like a charm!!

-1
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('data-attribute-id');
        var option_selected = jQuery(v).attr('data-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);


}
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.