Site icon MageComp Blog

How to Auto Select First Child Product of Configurable Product in Magento 2

How-to-Auto-Select-First-Child-Product-of-Configurable-Product-in-Magento-2

Hello Magento Friends,

Today I will discuss How to Auto Select First Child Product of Configurable Product in Magento 2.

Magento 2 allows creating a single product with several options which is known as configurable products. Learn How to Create Configurable Product Programmatically in Magento 2.

In Magento 2 when a configurable product is loaded, customers need to select combinations of the product. You can keep your most sellable products as auto-selected to increase the customer experience. With auto-select, the number of clicks for customers reduces that allows them to buy quickly.

So, let’s dive into the steps to know How to Auto Select the First Child Product of Configurable Product in Magento 2.

Steps to Auto Select First Child Product of Configurable Product in Magento 2:

For Dropdown:

Override the below Js file to your theme folder:

Vendor\magento\module-configurable-product\view\frontend\web\js\configurable.js

Paste the file in Your Custom Theme as below : 

app\design\frontend\Themes\Yourtheme\Magento_ConfigurableProduct\web\js\configurable.js

Place the below code in the function _fillSelect at the end of the function as shown in the image:

// Code added to select option
    if (i == 0) {
        this.options.values[attributeId] = options[i].id;
    }
}
//Code added to check if configurations are set in url and resets them if needed
if (window.location.href.indexOf('#') !== -1) {
    this._parseQueryParams(window.location.href.substr(window.location.href.indexOf('#') + 1));
}

With the implementation of the above step, the child product of the configurable product is auto-selected in the dropdown as shown below.

For Swatch:

Override the below Js file to your theme folder

File Path to Copy from:

vendor\magento\module-swatches\view\frontend\web\js\SwatchRenderer.js

Paste the file in Your Custom Theme as below

app\design\frontend\Themes\Yourtheme\Magento_Swatches\web\js\SwatchRenderer.js

Now, open this file and place the below code in the function _RenderControls at the end of this function as shown in the image:

For size Attribute:

var swatchLength = $('.swatch-attribute').length;
if(swatchLength >= 1){
    if($('.swatch-attribute').hasClass("size")){
        $('.swatch-option').first().trigger('click');
    }
}

For color Attribute:

jQuery('.swatch-option.color').first().click();

With the implementation of the above step, the child product of the configurable product is auto-selected for swatches as shown below.

Conclusion:

Hence, this way you can Auto Select First Child Product of Configurable Product in Magento 2. Feel free to reach me via the comment box in case of any trouble. Share the article with your friends and continue to be in touch with us!

Happy Coding!

Exit mobile version