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

Multi tool use
Multi tool use

Reverse dictionary where values are lists

How much of data wrangling is a data scientist's job?

Assassin's bullet with mercury

How does a predictive coding aid in lossless compression?

How could indestructible materials be used in power generation?

Why didn't Miles's spider sense work before?

Why is consensus so controversial in Britain?

What method can I use to design a dungeon difficult enough that the PCs can't make it through without killing them?

Alternative to sending password over mail?

Expand and Contract

Zip/Tar file compressed to larger size?

What mechanic is there to disable a threat instead of killing it?

What reasons are there for a Capitalist to oppose a 100% inheritance tax?

Mathematica command that allows it to read my intentions

Is "remove commented out code" correct English?

Can I run a new neutral wire to repair a broken circuit?

What killed these X2 caps?

CAST throwing error when run in stored procedure but not when run as raw query

Why are the 737's rear doors unusable in a water landing?

How would I stat a creature to be immune to everything but the Magic Missile spell? (just for fun)

How to compactly explain secondary and tertiary characters without resorting to stereotypes?

What is the most common color to indicate the input-field is disabled?

Can compressed videos be decoded back to their uncompresed original format?

Why can't we play rap on piano?



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







          gqUePGh,A,1,dbo8DARZXa4rvf2D6k,Z2nE3 S,AxIgy23HrSKL MXr
          LcmpKAmoPQysugCGW0XgYnUz

          Popular posts from this blog

          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

          Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

          Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?