I want to get product id on selecting swatch option.for that i have used code as given below. i am getting error of "Cannot read properties of undefined (reading 'options')" as per given screenshot.i am using Magento 2.4.4. if i print simple console.log(" hello world ") using this Js code this will execute but for select options it throws error.
error:- https://i.stack.imgur.com/cAsgD.png
/app/code/Vendor/Module/view/frontend/templates/product/view/type/default.phtml
<script>
requirejs(['jquery','underscore','Magento_Catalog/js/price-utils','mage/url'],
function(jQuery,_,flooring,priceUtils,urlBuilder){
jQuery(window).on('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');
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);
}
});
var new_found_ids = found_ids[0];
}
});
</script>
/app/code/Vendor/Module/view/frontend/layout/catalog_product_view_type_configurable.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="product.info.configurable">
<action method="setTemplate">
<argument name="template" xsi:type="string">Vendor_Module::product/view/type/default.phtml</argument>
</action>
</referenceBlock>
</body>
</page>