How to get selected simple product id in the configurable product from the dropdown options in Magento 2
-
15-04-2021 - |
Вопрос
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);
}
});
Решение
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>
Не связан с magento.stackexchange