When change a swatch option how to get a selected simple product id from configurable in category product listing page in Magento 2
when I select a swatch option, I was get a option id, from the option id how to get a simple product id from configurable product
Refer image : https://prnt.sc/ntsay1
code:
app\code\Cm\Preorder\view\frontend\templates\product\list.phtml
<script type="text/javascript">
requirejs(['jquery','underscore'], function(jQuery,_){
jQuery(window).load(function(){
jQuery( '[class*="swatch-opt"]' ).on('click', '.swatch-option', 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;
});
console.log(selected_options);
}
});
</script>
Best Answer
Create plugin to add quantity to the JS config to get from swatch renderer
Vendor/Module/etc/frontend/di.xml
Create a plugin file with quantity script below in vendor\module\Plugin\Block\ConfigurableProduct\Product\View\Type\Configurable.php
And your phtml looks like
You can get product quantity from swatches you need to override
vendor/magento/module-swatches/view/frontend/web/js/swatch-renderer.js
function_Rebuild
add following code..finally it looks like
You can add your logic here instead of adding scripts in phtml files.
To override js file copy from
vendor/magento/module-swatches/view/frontend/web/js/swatch-renderer.js
toapp/design/VENDOR/THEME/Magento_Swatches/web/js/swatch-renderer.js
Run upgrade and content deploy to see changes