phpjquerywordpresswoocommerceproduct-variations

Don't allow users to deselect variation swatch in WooCommerce


On our website for our brand Keylight we use the plugin Variation Swatches and Photos to let the customer select different variant options via color and image swatches. Every product has a default selection set up with the 'select option' option disabled for the variant selection. The customer is unfortunately still able to 'deselect' a chosen swatch by pressing it again which leads to confusion since that results in an invalid variation. The customer should always select one option for each attribute.

We searched on Google for a solution but the closest we got is with this post Don't allow users to deselect variation in WooCommerce. We applied this piece of code which does remove the selection in the dropdown option selection, but that doesn't work with swatches since you can still deselect a swatch.

What we want is when a customer presses a swatch for a second time, it doesn't unselect the swatch so that there always is a variation chosen. Does anybody know how we can achieve this?


Solution

  • With the following jquery you can detect if user clicks on already selected option which will make it unselected and prevent unselecting it. For that, place the following in a js file that is loaded on the product or create file and load it in your theme, or use plugin like "Simple Custom CSS and JS" or any other plugin out there.

    jQuery(function($) {
        $('.select-option.swatch-wrapper').on('click', function(e) {
            if ($(this).hasClass('selected')) {
                e.stopPropagation();
            }
        });
    });
    

    Updated code. Its abit overkill with checks but let me know if this works.

    jQuery(function($) {
        $(document).ready(function(){
            if($('.select-option.swatch-wrapper').length > 0 ) { 
                $('.select-option.swatch-wrapper').on('click', function(e) {
                    if ($(this).hasClass('selected')) {
                        e.stopPropagation();
                    }
                });
            }
        });
    });