Magento – How to Auto Select Swatch Option Values if Only One Exists on Magento 2.1 Product View

magento2

I'm trying to have swatch option values selected on the Product View page, if only one value exists.

If the user selects a product from the Category page, the product page displays with the attributes Color, Shape, and Size. Some products only have one color, one shape, and maybe two sizes. I want the color and shape values to be automatically selected when that page loads.

Thanks!

Best Answer

I had a similar task today - auto select size attribute, if there is only one option. Here is what I did:

In /Magento_Swatches/web/js/SwatchRenderer.js, in the _RenderControls function

lines 272-273 (in the end of $.each(this.options.jsonConfig.attributes) loop) add

if(item.options.length==1)
$widget.theOption = $widget.element.find('[attribute-id=' + item.id + '] .swatch-option')[0];

Here I just take my single size div element that should be selected

And then line 294 (at the bottom of the function):

if($widget.theOption != undefined) $widget.theOption.click();

Trigger click event to select size option

Related Topic