How to make auto select first child product of configurable product in magento2?Magento 2 configurable product variation dropdown attribute/s want to select automatically, if it has single option?How to select by default first swatches from dependent options color & size in magento 2Magento2 how to remove “choose an option” in configurable products drop downAuto Select simple products for configurable productHow we can select multiple sizes of configurable product from product details page?Configurable Products - how do I get data from the first child product?Magento 2 - Configurable product - Get parent product ID from child product IDmagento-configurable-auto-pricing at backendHow to Display child product image for configurable product in Magento2?Magento 2: How to set minimum amount option by default in product detail page for configurable options?Magento2 - programatically add to cart multiple configurable productsConfigurable Product - Get child product idAuto select first color swatches image in product page

Ambiguity in the definition of entropy

Different meanings of こわい

Can I hook these wires up to find the connection to a dead outlet?

How obscure is the use of 令 in 令和?

Fair gambler's ruin problem intuition

Finding the error in an argument

How dangerous is XSS

What do you call someone who asks many questions?

What is the opposite of "eschatology"?

How do conventional missiles fly?

ssTTsSTtRrriinInnnnNNNIiinngg

Was the Stack Exchange "Happy April Fools" page fitting with the '90's code?

Can someone clarify Hamming's notion of important problems in relation to modern academia?

How does a dynamic QR code work?

How could indestructible materials be used in power generation?

How to stretch the corners of this image so that it looks like a perfect rectangle?

How to install cross-compiler on Ubuntu 18.04?

Knowledge-based authentication using Domain-driven Design in C#

Processor speed limited at 0.4 Ghz

Do Iron Man suits sport waste management systems?

Is it possible to create a QR code using text?

How exploitable/balanced is this homebrew spell: Spell Permanency?

How do I exit BASH while loop using modulus operator?

Why do I get negative height?



How to make auto select first child product of configurable product in magento2?


Magento 2 configurable product variation dropdown attribute/s want to select automatically, if it has single option?How to select by default first swatches from dependent options color & size in magento 2Magento2 how to remove “choose an option” in configurable products drop downAuto Select simple products for configurable productHow we can select multiple sizes of configurable product from product details page?Configurable Products - how do I get data from the first child product?Magento 2 - Configurable product - Get parent product ID from child product IDmagento-configurable-auto-pricing at backendHow to Display child product image for configurable product in Magento2?Magento 2: How to set minimum amount option by default in product detail page for configurable options?Magento2 - programatically add to cart multiple configurable productsConfigurable Product - Get child product idAuto select first color swatches image in product page













2















I am trying to make auto select first child product from the configurable product in product detail page.



Is this possible?










share|improve this question




























    2















    I am trying to make auto select first child product from the configurable product in product detail page.



    Is this possible?










    share|improve this question


























      2












      2








      2








      I am trying to make auto select first child product from the configurable product in product detail page.



      Is this possible?










      share|improve this question
















      I am trying to make auto select first child product from the configurable product in product detail page.



      Is this possible?







      magento2 magento-2.1 configurable-product magento2.2 select






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 2 '18 at 15:09









      Amit Bera

      59.6k1676177




      59.6k1676177










      asked Jul 2 '18 at 14:59









      jafar pinjarjafar pinjar

      757414




      757414




















          1 Answer
          1






          active

          oldest

          votes


















          6














          For Dropdown:



          Override this file to your theme:




          vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js




          your theme file location will be:




          app/design/frontend/[vendor]/[theme]/Magento_ConfigurableProduct/web/js/configurable.js




          Replace the _fillSelect method under configurable.js



          _fillSelect: function (element) 
          var attributeId = element.id.replace(/[a-z]*/, ''),
          options = this._getAttributeOptions(attributeId),
          prevConfig,
          index = 1,
          allowedProducts,
          i,
          j;

          this._clearSelect(element);
          element.options[0] = new Option('', '');
          element.options[0].innerHTML = this.options.spConfig.chooseText;
          prevConfig = false;

          if (element.prevSetting)
          prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];


          if (options)
          for (i = 0; i < options.length; i++)
          allowedProducts = [];
          if (prevConfig)
          for (j = 0; j < options[i].products.length; j++)
          // prevConfig.config can be undefined
          if (prevConfig.config &&
          prevConfig.config.allowedProducts &&
          prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1)
          allowedProducts.push(options[i].products[j]);


          else
          allowedProducts = options[i].products.slice(0);


          if (allowedProducts.length > 0)
          options[i].allowedProducts = allowedProducts;
          element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id);
          if (typeof options[i].price !== 'undefined')
          element.options[index].setAttribute('price', options[i].prices);


          element.options[index].config = options[i];




          index++;

          // 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));


          ,


          For Swatch:
          Override the below file to your theme




          /module-swatches/view/frontend/web/js/SwatchRenderer.js




          And update the method _RenderControls



          _RenderControls: function () 
          var $widget = this,
          container = this.element,
          classes = this.options.classes,
          chooseText = this.options.jsonConfig.chooseText,
          selectedArray = []; // Variable declation for autoselect element array

          $widget.optionsMap = ;

          $.each(this.options.jsonConfig.attributes, function ()
          var item = this,
          controlLabelId = 'option-label-' + item.code + '-' + item.id,
          options = $widget._RenderSwatchOptions(item, controlLabelId),
          select = $widget._RenderSwatchSelect(item, chooseText),
          input = $widget._RenderFormInput(item),
          listLabel = '',
          label = '';

          // Show only swatch controls
          if ($widget.options.onlySwatches && !$widget.options.jsonSwatchConfig.hasOwnProperty(item.id))
          return;


          if ($widget.options.enableControlLabel)
          label +=
          '<span id="' + controlLabelId + '" class="' + classes.attributeLabelClass + '">' +
          item.label +
          '</span>' +
          '<span class="' + classes.attributeSelectedOptionLabelClass + '"></span>';


          if ($widget.inProductList)
          $widget.productForm.append(input);
          input = '';
          listLabel = 'aria-label="' + item.label + '"';
          else
          listLabel = 'aria-labelledby="' + controlLabelId + '"';


          // Create new control
          container.append(
          '<div class="' + classes.attributeClass + ' ' + item.code + '" ' +
          'attribute-code="' + item.code + '" ' +
          'attribute-id="' + item.id + '">' +
          label +
          '<div aria-activedescendant="" ' +
          'tabindex="0" ' +
          'aria-invalid="false" ' +
          'aria-required="true" ' +
          'role="listbox" ' + listLabel +
          'class="' + classes.attributeOptionsWrapper + ' clearfix">' +
          options + select +
          '</div>' + input +
          '</div>'
          );

          $widget.optionsMap[item.id] = ;

          // Aggregate options array to hash (key => value)
          $.each(item.options, function ()
          if (this.products.length > 0)
          $widget.optionsMap[item.id][this.id] =
          price: parseInt(
          $widget.options.jsonConfig.optionPrices[this.products[0]].finalPrice.amount,
          10
          ),
          products: this.products
          ;

          );
          //Create array for Autoselect swatch
          selectedArray.push($widget.element.find('[attribute-id=' + item.id + '] .swatch-option')[0]);
          );


          // Connect Tooltip
          container
          .find('[option-type="1"], [option-type="2"], [option-type="0"], [option-type="3"]')
          .SwatchRendererTooltip();

          // Hide all elements below more button
          $('.' + classes.moreButton).nextAll().hide();

          // Handle events like click or change
          $widget._EventListener();

          // Rewind options
          $widget._Rewind(container);

          //Emulate click on all swatches from Request
          $widget._EmulateSelected($.parseQuery());
          $widget._EmulateSelected($widget._getSelectedAttributes());

          //Trigger click for Autoselect first option swatch
          $.each(selectedArray, function ()
          if(this != undefined) this.click();
          );

          ,





          share|improve this answer

























          • Hello, i am using module swatch , the above code is for drop downs i guess, can we make it work for swatches also?

            – jafar pinjar
            Jul 2 '18 at 15:42











          • Please check my updated answer.

            – Sukumar Gorai
            Jul 2 '18 at 15:46











          • checked but i am getting $.parseParams is not a function error

            – jafar pinjar
            Jul 2 '18 at 15:54











          • Happy to help!. Upvote please when reach to 15.

            – Sukumar Gorai
            Jul 3 '18 at 9:38











          • Sure!!! . i will upvote

            – jafar pinjar
            Jul 3 '18 at 9:40











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "479"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f232072%2fhow-to-make-auto-select-first-child-product-of-configurable-product-in-magento2%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          6














          For Dropdown:



          Override this file to your theme:




          vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js




          your theme file location will be:




          app/design/frontend/[vendor]/[theme]/Magento_ConfigurableProduct/web/js/configurable.js




          Replace the _fillSelect method under configurable.js



          _fillSelect: function (element) 
          var attributeId = element.id.replace(/[a-z]*/, ''),
          options = this._getAttributeOptions(attributeId),
          prevConfig,
          index = 1,
          allowedProducts,
          i,
          j;

          this._clearSelect(element);
          element.options[0] = new Option('', '');
          element.options[0].innerHTML = this.options.spConfig.chooseText;
          prevConfig = false;

          if (element.prevSetting)
          prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];


          if (options)
          for (i = 0; i < options.length; i++)
          allowedProducts = [];
          if (prevConfig)
          for (j = 0; j < options[i].products.length; j++)
          // prevConfig.config can be undefined
          if (prevConfig.config &&
          prevConfig.config.allowedProducts &&
          prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1)
          allowedProducts.push(options[i].products[j]);


          else
          allowedProducts = options[i].products.slice(0);


          if (allowedProducts.length > 0)
          options[i].allowedProducts = allowedProducts;
          element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id);
          if (typeof options[i].price !== 'undefined')
          element.options[index].setAttribute('price', options[i].prices);


          element.options[index].config = options[i];




          index++;

          // 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));


          ,


          For Swatch:
          Override the below file to your theme




          /module-swatches/view/frontend/web/js/SwatchRenderer.js




          And update the method _RenderControls



          _RenderControls: function () 
          var $widget = this,
          container = this.element,
          classes = this.options.classes,
          chooseText = this.options.jsonConfig.chooseText,
          selectedArray = []; // Variable declation for autoselect element array

          $widget.optionsMap = ;

          $.each(this.options.jsonConfig.attributes, function ()
          var item = this,
          controlLabelId = 'option-label-' + item.code + '-' + item.id,
          options = $widget._RenderSwatchOptions(item, controlLabelId),
          select = $widget._RenderSwatchSelect(item, chooseText),
          input = $widget._RenderFormInput(item),
          listLabel = '',
          label = '';

          // Show only swatch controls
          if ($widget.options.onlySwatches && !$widget.options.jsonSwatchConfig.hasOwnProperty(item.id))
          return;


          if ($widget.options.enableControlLabel)
          label +=
          '<span id="' + controlLabelId + '" class="' + classes.attributeLabelClass + '">' +
          item.label +
          '</span>' +
          '<span class="' + classes.attributeSelectedOptionLabelClass + '"></span>';


          if ($widget.inProductList)
          $widget.productForm.append(input);
          input = '';
          listLabel = 'aria-label="' + item.label + '"';
          else
          listLabel = 'aria-labelledby="' + controlLabelId + '"';


          // Create new control
          container.append(
          '<div class="' + classes.attributeClass + ' ' + item.code + '" ' +
          'attribute-code="' + item.code + '" ' +
          'attribute-id="' + item.id + '">' +
          label +
          '<div aria-activedescendant="" ' +
          'tabindex="0" ' +
          'aria-invalid="false" ' +
          'aria-required="true" ' +
          'role="listbox" ' + listLabel +
          'class="' + classes.attributeOptionsWrapper + ' clearfix">' +
          options + select +
          '</div>' + input +
          '</div>'
          );

          $widget.optionsMap[item.id] = ;

          // Aggregate options array to hash (key => value)
          $.each(item.options, function ()
          if (this.products.length > 0)
          $widget.optionsMap[item.id][this.id] =
          price: parseInt(
          $widget.options.jsonConfig.optionPrices[this.products[0]].finalPrice.amount,
          10
          ),
          products: this.products
          ;

          );
          //Create array for Autoselect swatch
          selectedArray.push($widget.element.find('[attribute-id=' + item.id + '] .swatch-option')[0]);
          );


          // Connect Tooltip
          container
          .find('[option-type="1"], [option-type="2"], [option-type="0"], [option-type="3"]')
          .SwatchRendererTooltip();

          // Hide all elements below more button
          $('.' + classes.moreButton).nextAll().hide();

          // Handle events like click or change
          $widget._EventListener();

          // Rewind options
          $widget._Rewind(container);

          //Emulate click on all swatches from Request
          $widget._EmulateSelected($.parseQuery());
          $widget._EmulateSelected($widget._getSelectedAttributes());

          //Trigger click for Autoselect first option swatch
          $.each(selectedArray, function ()
          if(this != undefined) this.click();
          );

          ,





          share|improve this answer

























          • Hello, i am using module swatch , the above code is for drop downs i guess, can we make it work for swatches also?

            – jafar pinjar
            Jul 2 '18 at 15:42











          • Please check my updated answer.

            – Sukumar Gorai
            Jul 2 '18 at 15:46











          • checked but i am getting $.parseParams is not a function error

            – jafar pinjar
            Jul 2 '18 at 15:54











          • Happy to help!. Upvote please when reach to 15.

            – Sukumar Gorai
            Jul 3 '18 at 9:38











          • Sure!!! . i will upvote

            – jafar pinjar
            Jul 3 '18 at 9:40















          6














          For Dropdown:



          Override this file to your theme:




          vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js




          your theme file location will be:




          app/design/frontend/[vendor]/[theme]/Magento_ConfigurableProduct/web/js/configurable.js




          Replace the _fillSelect method under configurable.js



          _fillSelect: function (element) 
          var attributeId = element.id.replace(/[a-z]*/, ''),
          options = this._getAttributeOptions(attributeId),
          prevConfig,
          index = 1,
          allowedProducts,
          i,
          j;

          this._clearSelect(element);
          element.options[0] = new Option('', '');
          element.options[0].innerHTML = this.options.spConfig.chooseText;
          prevConfig = false;

          if (element.prevSetting)
          prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];


          if (options)
          for (i = 0; i < options.length; i++)
          allowedProducts = [];
          if (prevConfig)
          for (j = 0; j < options[i].products.length; j++)
          // prevConfig.config can be undefined
          if (prevConfig.config &&
          prevConfig.config.allowedProducts &&
          prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1)
          allowedProducts.push(options[i].products[j]);


          else
          allowedProducts = options[i].products.slice(0);


          if (allowedProducts.length > 0)
          options[i].allowedProducts = allowedProducts;
          element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id);
          if (typeof options[i].price !== 'undefined')
          element.options[index].setAttribute('price', options[i].prices);


          element.options[index].config = options[i];




          index++;

          // 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));


          ,


          For Swatch:
          Override the below file to your theme




          /module-swatches/view/frontend/web/js/SwatchRenderer.js




          And update the method _RenderControls



          _RenderControls: function () 
          var $widget = this,
          container = this.element,
          classes = this.options.classes,
          chooseText = this.options.jsonConfig.chooseText,
          selectedArray = []; // Variable declation for autoselect element array

          $widget.optionsMap = ;

          $.each(this.options.jsonConfig.attributes, function ()
          var item = this,
          controlLabelId = 'option-label-' + item.code + '-' + item.id,
          options = $widget._RenderSwatchOptions(item, controlLabelId),
          select = $widget._RenderSwatchSelect(item, chooseText),
          input = $widget._RenderFormInput(item),
          listLabel = '',
          label = '';

          // Show only swatch controls
          if ($widget.options.onlySwatches && !$widget.options.jsonSwatchConfig.hasOwnProperty(item.id))
          return;


          if ($widget.options.enableControlLabel)
          label +=
          '<span id="' + controlLabelId + '" class="' + classes.attributeLabelClass + '">' +
          item.label +
          '</span>' +
          '<span class="' + classes.attributeSelectedOptionLabelClass + '"></span>';


          if ($widget.inProductList)
          $widget.productForm.append(input);
          input = '';
          listLabel = 'aria-label="' + item.label + '"';
          else
          listLabel = 'aria-labelledby="' + controlLabelId + '"';


          // Create new control
          container.append(
          '<div class="' + classes.attributeClass + ' ' + item.code + '" ' +
          'attribute-code="' + item.code + '" ' +
          'attribute-id="' + item.id + '">' +
          label +
          '<div aria-activedescendant="" ' +
          'tabindex="0" ' +
          'aria-invalid="false" ' +
          'aria-required="true" ' +
          'role="listbox" ' + listLabel +
          'class="' + classes.attributeOptionsWrapper + ' clearfix">' +
          options + select +
          '</div>' + input +
          '</div>'
          );

          $widget.optionsMap[item.id] = ;

          // Aggregate options array to hash (key => value)
          $.each(item.options, function ()
          if (this.products.length > 0)
          $widget.optionsMap[item.id][this.id] =
          price: parseInt(
          $widget.options.jsonConfig.optionPrices[this.products[0]].finalPrice.amount,
          10
          ),
          products: this.products
          ;

          );
          //Create array for Autoselect swatch
          selectedArray.push($widget.element.find('[attribute-id=' + item.id + '] .swatch-option')[0]);
          );


          // Connect Tooltip
          container
          .find('[option-type="1"], [option-type="2"], [option-type="0"], [option-type="3"]')
          .SwatchRendererTooltip();

          // Hide all elements below more button
          $('.' + classes.moreButton).nextAll().hide();

          // Handle events like click or change
          $widget._EventListener();

          // Rewind options
          $widget._Rewind(container);

          //Emulate click on all swatches from Request
          $widget._EmulateSelected($.parseQuery());
          $widget._EmulateSelected($widget._getSelectedAttributes());

          //Trigger click for Autoselect first option swatch
          $.each(selectedArray, function ()
          if(this != undefined) this.click();
          );

          ,





          share|improve this answer

























          • Hello, i am using module swatch , the above code is for drop downs i guess, can we make it work for swatches also?

            – jafar pinjar
            Jul 2 '18 at 15:42











          • Please check my updated answer.

            – Sukumar Gorai
            Jul 2 '18 at 15:46











          • checked but i am getting $.parseParams is not a function error

            – jafar pinjar
            Jul 2 '18 at 15:54











          • Happy to help!. Upvote please when reach to 15.

            – Sukumar Gorai
            Jul 3 '18 at 9:38











          • Sure!!! . i will upvote

            – jafar pinjar
            Jul 3 '18 at 9:40













          6












          6








          6







          For Dropdown:



          Override this file to your theme:




          vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js




          your theme file location will be:




          app/design/frontend/[vendor]/[theme]/Magento_ConfigurableProduct/web/js/configurable.js




          Replace the _fillSelect method under configurable.js



          _fillSelect: function (element) 
          var attributeId = element.id.replace(/[a-z]*/, ''),
          options = this._getAttributeOptions(attributeId),
          prevConfig,
          index = 1,
          allowedProducts,
          i,
          j;

          this._clearSelect(element);
          element.options[0] = new Option('', '');
          element.options[0].innerHTML = this.options.spConfig.chooseText;
          prevConfig = false;

          if (element.prevSetting)
          prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];


          if (options)
          for (i = 0; i < options.length; i++)
          allowedProducts = [];
          if (prevConfig)
          for (j = 0; j < options[i].products.length; j++)
          // prevConfig.config can be undefined
          if (prevConfig.config &&
          prevConfig.config.allowedProducts &&
          prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1)
          allowedProducts.push(options[i].products[j]);


          else
          allowedProducts = options[i].products.slice(0);


          if (allowedProducts.length > 0)
          options[i].allowedProducts = allowedProducts;
          element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id);
          if (typeof options[i].price !== 'undefined')
          element.options[index].setAttribute('price', options[i].prices);


          element.options[index].config = options[i];




          index++;

          // 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));


          ,


          For Swatch:
          Override the below file to your theme




          /module-swatches/view/frontend/web/js/SwatchRenderer.js




          And update the method _RenderControls



          _RenderControls: function () 
          var $widget = this,
          container = this.element,
          classes = this.options.classes,
          chooseText = this.options.jsonConfig.chooseText,
          selectedArray = []; // Variable declation for autoselect element array

          $widget.optionsMap = ;

          $.each(this.options.jsonConfig.attributes, function ()
          var item = this,
          controlLabelId = 'option-label-' + item.code + '-' + item.id,
          options = $widget._RenderSwatchOptions(item, controlLabelId),
          select = $widget._RenderSwatchSelect(item, chooseText),
          input = $widget._RenderFormInput(item),
          listLabel = '',
          label = '';

          // Show only swatch controls
          if ($widget.options.onlySwatches && !$widget.options.jsonSwatchConfig.hasOwnProperty(item.id))
          return;


          if ($widget.options.enableControlLabel)
          label +=
          '<span id="' + controlLabelId + '" class="' + classes.attributeLabelClass + '">' +
          item.label +
          '</span>' +
          '<span class="' + classes.attributeSelectedOptionLabelClass + '"></span>';


          if ($widget.inProductList)
          $widget.productForm.append(input);
          input = '';
          listLabel = 'aria-label="' + item.label + '"';
          else
          listLabel = 'aria-labelledby="' + controlLabelId + '"';


          // Create new control
          container.append(
          '<div class="' + classes.attributeClass + ' ' + item.code + '" ' +
          'attribute-code="' + item.code + '" ' +
          'attribute-id="' + item.id + '">' +
          label +
          '<div aria-activedescendant="" ' +
          'tabindex="0" ' +
          'aria-invalid="false" ' +
          'aria-required="true" ' +
          'role="listbox" ' + listLabel +
          'class="' + classes.attributeOptionsWrapper + ' clearfix">' +
          options + select +
          '</div>' + input +
          '</div>'
          );

          $widget.optionsMap[item.id] = ;

          // Aggregate options array to hash (key => value)
          $.each(item.options, function ()
          if (this.products.length > 0)
          $widget.optionsMap[item.id][this.id] =
          price: parseInt(
          $widget.options.jsonConfig.optionPrices[this.products[0]].finalPrice.amount,
          10
          ),
          products: this.products
          ;

          );
          //Create array for Autoselect swatch
          selectedArray.push($widget.element.find('[attribute-id=' + item.id + '] .swatch-option')[0]);
          );


          // Connect Tooltip
          container
          .find('[option-type="1"], [option-type="2"], [option-type="0"], [option-type="3"]')
          .SwatchRendererTooltip();

          // Hide all elements below more button
          $('.' + classes.moreButton).nextAll().hide();

          // Handle events like click or change
          $widget._EventListener();

          // Rewind options
          $widget._Rewind(container);

          //Emulate click on all swatches from Request
          $widget._EmulateSelected($.parseQuery());
          $widget._EmulateSelected($widget._getSelectedAttributes());

          //Trigger click for Autoselect first option swatch
          $.each(selectedArray, function ()
          if(this != undefined) this.click();
          );

          ,





          share|improve this answer















          For Dropdown:



          Override this file to your theme:




          vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js




          your theme file location will be:




          app/design/frontend/[vendor]/[theme]/Magento_ConfigurableProduct/web/js/configurable.js




          Replace the _fillSelect method under configurable.js



          _fillSelect: function (element) 
          var attributeId = element.id.replace(/[a-z]*/, ''),
          options = this._getAttributeOptions(attributeId),
          prevConfig,
          index = 1,
          allowedProducts,
          i,
          j;

          this._clearSelect(element);
          element.options[0] = new Option('', '');
          element.options[0].innerHTML = this.options.spConfig.chooseText;
          prevConfig = false;

          if (element.prevSetting)
          prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];


          if (options)
          for (i = 0; i < options.length; i++)
          allowedProducts = [];
          if (prevConfig)
          for (j = 0; j < options[i].products.length; j++)
          // prevConfig.config can be undefined
          if (prevConfig.config &&
          prevConfig.config.allowedProducts &&
          prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1)
          allowedProducts.push(options[i].products[j]);


          else
          allowedProducts = options[i].products.slice(0);


          if (allowedProducts.length > 0)
          options[i].allowedProducts = allowedProducts;
          element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id);
          if (typeof options[i].price !== 'undefined')
          element.options[index].setAttribute('price', options[i].prices);


          element.options[index].config = options[i];




          index++;

          // 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));


          ,


          For Swatch:
          Override the below file to your theme




          /module-swatches/view/frontend/web/js/SwatchRenderer.js




          And update the method _RenderControls



          _RenderControls: function () 
          var $widget = this,
          container = this.element,
          classes = this.options.classes,
          chooseText = this.options.jsonConfig.chooseText,
          selectedArray = []; // Variable declation for autoselect element array

          $widget.optionsMap = ;

          $.each(this.options.jsonConfig.attributes, function ()
          var item = this,
          controlLabelId = 'option-label-' + item.code + '-' + item.id,
          options = $widget._RenderSwatchOptions(item, controlLabelId),
          select = $widget._RenderSwatchSelect(item, chooseText),
          input = $widget._RenderFormInput(item),
          listLabel = '',
          label = '';

          // Show only swatch controls
          if ($widget.options.onlySwatches && !$widget.options.jsonSwatchConfig.hasOwnProperty(item.id))
          return;


          if ($widget.options.enableControlLabel)
          label +=
          '<span id="' + controlLabelId + '" class="' + classes.attributeLabelClass + '">' +
          item.label +
          '</span>' +
          '<span class="' + classes.attributeSelectedOptionLabelClass + '"></span>';


          if ($widget.inProductList)
          $widget.productForm.append(input);
          input = '';
          listLabel = 'aria-label="' + item.label + '"';
          else
          listLabel = 'aria-labelledby="' + controlLabelId + '"';


          // Create new control
          container.append(
          '<div class="' + classes.attributeClass + ' ' + item.code + '" ' +
          'attribute-code="' + item.code + '" ' +
          'attribute-id="' + item.id + '">' +
          label +
          '<div aria-activedescendant="" ' +
          'tabindex="0" ' +
          'aria-invalid="false" ' +
          'aria-required="true" ' +
          'role="listbox" ' + listLabel +
          'class="' + classes.attributeOptionsWrapper + ' clearfix">' +
          options + select +
          '</div>' + input +
          '</div>'
          );

          $widget.optionsMap[item.id] = ;

          // Aggregate options array to hash (key => value)
          $.each(item.options, function ()
          if (this.products.length > 0)
          $widget.optionsMap[item.id][this.id] =
          price: parseInt(
          $widget.options.jsonConfig.optionPrices[this.products[0]].finalPrice.amount,
          10
          ),
          products: this.products
          ;

          );
          //Create array for Autoselect swatch
          selectedArray.push($widget.element.find('[attribute-id=' + item.id + '] .swatch-option')[0]);
          );


          // Connect Tooltip
          container
          .find('[option-type="1"], [option-type="2"], [option-type="0"], [option-type="3"]')
          .SwatchRendererTooltip();

          // Hide all elements below more button
          $('.' + classes.moreButton).nextAll().hide();

          // Handle events like click or change
          $widget._EventListener();

          // Rewind options
          $widget._Rewind(container);

          //Emulate click on all swatches from Request
          $widget._EmulateSelected($.parseQuery());
          $widget._EmulateSelected($widget._getSelectedAttributes());

          //Trigger click for Autoselect first option swatch
          $.each(selectedArray, function ()
          if(this != undefined) this.click();
          );

          ,






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jul 3 '18 at 9:02

























          answered Jul 2 '18 at 15:17









          Sukumar GoraiSukumar Gorai

          6,9303729




          6,9303729












          • Hello, i am using module swatch , the above code is for drop downs i guess, can we make it work for swatches also?

            – jafar pinjar
            Jul 2 '18 at 15:42











          • Please check my updated answer.

            – Sukumar Gorai
            Jul 2 '18 at 15:46











          • checked but i am getting $.parseParams is not a function error

            – jafar pinjar
            Jul 2 '18 at 15:54











          • Happy to help!. Upvote please when reach to 15.

            – Sukumar Gorai
            Jul 3 '18 at 9:38











          • Sure!!! . i will upvote

            – jafar pinjar
            Jul 3 '18 at 9:40

















          • Hello, i am using module swatch , the above code is for drop downs i guess, can we make it work for swatches also?

            – jafar pinjar
            Jul 2 '18 at 15:42











          • Please check my updated answer.

            – Sukumar Gorai
            Jul 2 '18 at 15:46











          • checked but i am getting $.parseParams is not a function error

            – jafar pinjar
            Jul 2 '18 at 15:54











          • Happy to help!. Upvote please when reach to 15.

            – Sukumar Gorai
            Jul 3 '18 at 9:38











          • Sure!!! . i will upvote

            – jafar pinjar
            Jul 3 '18 at 9:40
















          Hello, i am using module swatch , the above code is for drop downs i guess, can we make it work for swatches also?

          – jafar pinjar
          Jul 2 '18 at 15:42





          Hello, i am using module swatch , the above code is for drop downs i guess, can we make it work for swatches also?

          – jafar pinjar
          Jul 2 '18 at 15:42













          Please check my updated answer.

          – Sukumar Gorai
          Jul 2 '18 at 15:46





          Please check my updated answer.

          – Sukumar Gorai
          Jul 2 '18 at 15:46













          checked but i am getting $.parseParams is not a function error

          – jafar pinjar
          Jul 2 '18 at 15:54





          checked but i am getting $.parseParams is not a function error

          – jafar pinjar
          Jul 2 '18 at 15:54













          Happy to help!. Upvote please when reach to 15.

          – Sukumar Gorai
          Jul 3 '18 at 9:38





          Happy to help!. Upvote please when reach to 15.

          – Sukumar Gorai
          Jul 3 '18 at 9:38













          Sure!!! . i will upvote

          – jafar pinjar
          Jul 3 '18 at 9:40





          Sure!!! . i will upvote

          – jafar pinjar
          Jul 3 '18 at 9:40

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Magento Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f232072%2fhow-to-make-auto-select-first-child-product-of-configurable-product-in-magento2%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Nidaros erkebispedøme

          Birsay

          Where did Arya get these scars? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Favourite questions and answers from the 1st quarter of 2019Why did Arya refuse to end it?Has the pronunciation of Arya Stark's name changed?Has Arya forgiven people?Why did Arya Stark lose her vision?Why can Arya still use the faces?Has the Narrow Sea become narrower?Does Arya Stark know how to make poisons outside of the House of Black and White?Why did Nymeria leave Arya?Why did Arya not kill the Lannister soldiers she encountered in the Riverlands?What is the current canonical age of Sansa, Bran and Arya Stark?