Menu Close

    How to get the selected swatches option on the product page.

    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)

    Screenshot-from-2023-01-06-15-48-24

    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

    Start your headless eCommerce
    now.
    Read More

    I’ll be back soon 😉

    . . .
    Discuss on Helpdesk

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top