1

How can I get the child product Id of Configurable product on selecting swatch option. I have used following code

<script type="text/javascript">
requirejs(['jquery','underscore'], function(jQuery,_){
        jQuery(document).ready(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');
            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);
            }
        });
        if (found_ids.length) {
            var selected_product_id = found_ids[0];
            jQuery('.myli').css('display','none');
            jQuery('#div'+selected_product_id).toggle();
        }
    }
});

Following this line give Uncaught TypeError: Cannot read properties of undefined (reading 'options')

jQuery('[data-role=swatch-options]').data('mageSwatchRenderer').options.jsonConfig.index;

enter image description here

1 Answer 1

0

Wrap your custom js code in document.ready

<script>
    require([
    'jquery'
    ], function () {
      jQuery(document).ready(function() {
         //add your code here
      });
    });
</script>
1
  • Hello Prashant thanks for your reply I have updated my code in question now you can check Oct 17, 2022 at 11:19

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.