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

Is it possible to map the firing of neurons in the human brain so as to stimulate artificial memories in someone else?

Mathematica command that allows it to read my intentions

Does the Idaho Potato Commission associate potato skins with healthy eating?

What is the opposite of "eschatology"?

Is there an online compendium of Rav Moshe teshuvos in English that exists?

Finding the error in an argument

One verb to replace 'be a member of' a club

Ambiguity in the definition of entropy

Using "tail" to follow a file without displaying the most recent lines

What Exploit Are These User Agents Trying to Use?

What is the fastest integer factorization to break RSA?

How do I exit BASH while loop using modulus operator?

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

How much mains leakage does an Ethernet connection to a PC induce, and what is the operating leakage path?

Theorists sure want true answers to this!

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

Why is it a bad idea to hire a hitman to eliminate most corrupt politicians?

Why didn't Boeing produce its own regional jet?

Can a virus destroy the BIOS of a modern computer?

Could the museum Saturn V's be refitted for one more flight?

Am I breaking OOP practice with this architecture?

Forgetting the musical notes while performing in concert

How obscure is the use of 令 in 令和?

GFCI outlets - can they be repaired? Are they really needed at the end of a circuit?



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

          Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

          Magento 2 disable Secret Key on URL's from terminal The Next CEO of Stack OverflowMagento 2 Shortcut/GUI tool to perform commandline tasks for windowsIn menu add configuration linkMagento oAuth : Generating access token and access secretMagento 2 security key issue in Third-Party API redirect URIPublic actions in admin controllersHow to Disable Cache in Custom WidgetURL Key not changing in Magento 2Product URL Key gets deleted when importing custom options - Magento 2Problem with reindex terminalMagento 2 - bin/magento Commands not working in Cpanel Terminal

          Aasi (pallopeli) Navigointivalikko