1

How to get selected simple product id in the configurable product from the dropdown options in Magento 2

The below code works fine with "Swatch Option" but not work with the "Dropdown Option"

  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 = [];
            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);
        }
    });

enter image description here

1 Answer 1

0

The below code works for the "Dropdown" Option.

<script type="text/javascript">
require(['jquery','underscore'], function(jQuery,_){
    var confProductId = jQuery('.price-box').attr('data-product-id');
    jQuery(".product-options-wrapper select[id^='attribute']").last().on('change', function() {
      setTimeout(function (){
        simpleId=jQuery("input[name=selected_configurable_option]").val();
        alert(simpleId);
    
        var data = [];
        var $el=jQuery(".product-options-wrapper select[id^='attribute']");
        $el.each(function(){
            data.push(jQuery(this).attr('id').replace('attribute', ''));
       });
       // do your stuff here
       }, 500); 
    });
});
</script>

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.