Magento – How to Auto Select Color Option for Products with Only One Color (configurable product)

custom-attributesjquerymagento2magento2.2.3

I have some configurable products with a custom color swatches attribute. Lot of them have just one color options, so i 'd like to mark the option as selected in the product page. I added a custom js script to the product page but it works just in chrome console, not in the website.
(Jquery is inthe required function, i don't know why stack's editor does not read it as code)

  var number = $('.swatch-attribute .color').length;
  if(number==1){
    $('.swatch-attribute .color').click();
  }

It does not work and the color option it is still not selected, how can i fix it?

Best Answer

I suggest running that code using an on load event listener.

if (window.addEventListener) // W3C standard
{
  window.addEventListener('load', configurabledefaults, false); // NB **not** 'onload'
} 
else if (window.attachEvent) // Microsoft
{
  window.attachEvent('onload', configurabledefaults);
}
function configurabledefaults {
var number = $('.swatch-attribute .color').length;
if(number==1){$('.swatch-attribute .color').click();}
}

See the following link about multiple onload events.

Multiple window on load events

Related Topic