Get Swatch Text Product id of Configurable Product in Detail Page through Jquery Magento2




Add This Script in Detail Page You will get id of selected Product




<script type="text/javascript">
  
   require(['jquery'],function(jQuery){
  jQuery('body').on('click', '.swatch-option', function(e) {
    var swatchid = jQuery('.swatch-attribute').attr('option-selected');
     if (swatchid) {

     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;}
            if(attribute_id || option_selected){
            selected_options[attribute_id] = option_selected;
           }
        });

      
        console.log(selected_options); 
       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);
            }
            //console.log(product_id);
            if(productIsSelected(attributes, selected_options)){

                found_ids.push(product_id);
            } 
        });

        console.log(found_ids);
        if (found_ids) {

        alert(found_ids)  ////Here Product id founded

        }
    }



</script>

Comments

Popular posts from this blog

Getting product Image in PHTML in Magento2

Get Customer Address with customer ID programmatically Magento2