Sometimes we need to add some restrictions on selecting the swatches option, so in this blog, we will discuss how to get the selected swatches option with the help of javascript on the catalog product view page.
<script type="text/javascript"> requirejs(['jquery','underscore'], function($, _) { $(window).load(function(){ $( '[class*="swatch-opt"]' ).on('click', '.swatch-option', function() { getSelectedSwatchesOptions(); }); }); function getSelectedSwatchesOptions() { var selected_options = {}; $('div.swatch-attribute').each(function(key, value){ var attribute_id = $(value).attr('attribute-id'); var option_selected = $(value).attr('option-selected'); if(!attribute_id || !option_selected) { return; } selected_options[attribute_id] = option_selected; }); console.log(selected_options); } }); </script>
Selected two swatches (Size:L, Brand: Puma)
After selecting these swatches you will get their selected option id and attribute id in your console like this:
Object { 35: "11" 36: "14" }
Where 35 is the attribute id and 11 is the selected option id, now based on this option and attribute id you can do whatever you want, like restrict add to cart, and many things.
This is all for now, hope this will help. For any doubts, you can comment below
I’ll be back soon 😉
Be the first to comment.