Magento 2 Get selected simple product id in configurable product
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');
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: