How to make configurable options autoselected on Product view page

How to make configurable options autoselected on Product view page

If you ever tried to do anything with Magento configurable products view page, most likely you needed changes in  /js/varien/product.js in case you wanted to manipulate dropdowns.

This will be one of the ways to do it.

Basically, what we need to do in order to make initial selection of a product is the following:

Open this file: /app/design/frontend/default/your_theme/template/catalog/product/view/type/options/configurable.phtml

Right below

var spConfig = new Product.Config(< ?php echo $this->getJsonConfig() ?>);

add this JavaScript code:

//we create new function
 
spConfig.setInitialState = function(dropdown_id)
{
 
//select dropdown
 
var dropdown = $(dropdown_id);
//remove empty option from dropdown so it is not selectable after initial selection
 
dropdown[0].remove();
//change selections in dropdowns
for(index = 0; index < dropdown.length; index++)
{
 
if(dropdown[index].value != "")
{
dropdown.selectedIndex = index;
 
var element = dropdown;
var event = 'change';
 
//fire events
if(document.createEventObject)
{
 
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else
{
 
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true );
return !element.dispatchEvent(evt);
}
}
}
 
};
 
<!--?php foreach($_attributes as $_attribute): ?-->
spConfig.setInitialState("attribute< ?php echo $_attribute->getAttributeId() ?>")
< ?php endforeach; ?>

That’s it. I hope you can find this usable, however don’t use it on production site without extensive testing.

As you can see, all prototype functions in Magento (and in general) can be added as new into already existing class.

Same way you could override existing methods in existing classes.

I have coded this feature for the purpose of this article and I’m not claiming that it is production ready. It is only for informative purposes.

You made it all the way down here so you must have enjoyed this post! You may also like:

Sorry, we can’t ship there Sasa Brankovic
Sasa Brankovic, | 12

Sorry, we can’t ship there

Shell script for converting configurable to grouped products Tsvetan Stoychev
Tsvetan Stoychev, | 5

Shell script for converting configurable to grouped products

Getting selected simple product id in configurable product on client side. Goran Sambolic
Goran Sambolic, | 24

Getting selected simple product id in configurable product on client side.

30 comments

  1. Hi,
    I want to reload a part of the product view page(a template from an extension) of the configurable product when the configurable option is selected. Can you please help me with this?

  2. Very nice, thanks for sharing this! Saved me lots of time and great ideas that I could use as a starting point for what I need to do.

  3. Very nice, thanks for sharing this! Saved me lots of time and great ideas that I could use as a starting point for what I need to do.

  4. Heyy Tomas, how can I reset below swatch selections when above changes? Or remove and unselect unavailable swatches ? In 1.9.2.4?

  5. It works but unfortunately it removes also the ‘disabled’ option. So, if I have a black small shirt and a white medium shirt:

    normal behaviour: when I choose the color, the size that don’t match with the color gets disabled and user can’t click it

    your modification behaviour: no matter what color I choose, the second dropdown shows always the first option, no matter if it is available or not. User can choose the option that normally he wouldn’t be allowed to choose because option is not disabled in html. When user tries to add to cart with the wrong option combination, a warning message pops up saying that he has to choose the right combination but because there is no other indication about what options are enabled the user can’t know what the correct combination is.

    Is there a way to preserve default magento functionality (which is: automatically set to disabled options in second dropdown which don’t match with what user chose in first dropdown) AND remove the useless ‘choose an option’ text?

  6. hi
    using v1.9+ but could not get this to work. I have 2 attributes – color then size. I want the options to disappear from size when a color is chosen but i also want the size drop down not clickable until the color is chosen, is this possible?

  7. Hi,
    I am using Magento ver. 1.9.0.1
    I want to change please select option for configurable product’s attributes. I added three custom attribute for shirt, pant and trouser. I want to show select shirt size for shirt attribute, select pant size for pant attribute and select trouser size for trouser attribute in front end. But currently it is showing please select in all the three attributes of configurable product.
    can you please help me to solve this ?
    Default code for configurable product in /app/design/frontend/rwd/default/template/catalog/product/view/type/options is
    getProduct();
    $_attributes = Mage::helper(‘core’)->decorateArray($this->getAllowAttributes());
    $_jsonConfig = $this->getJsonConfig();
    $_renderers = $this->getChild(‘attr_renderers’)->getSortedChildren();
    ?>
    isSaleable() && count($_attributes)):?>

    getChild(‘attr_renderers’)->getChild($_rendererName);
    if (method_exists($_renderer, ‘shouldRender’) && $_renderer->shouldRender($_product, $_attribute, $_jsonConfig)):
    $_renderer->setProduct($_product);
    $_renderer->setAttributeObj($_attribute);
    echo $_renderer->toHtml();
    $_rendered = true;
    break;
    endif;
    endforeach;

    if (!$_rendered):
    ?>
    *getLabel() ?>
    <dddecoratedIsLast){?> class=”last”>

    <select name="super_attribute[getAttributeId() ?>]” id=”attributegetAttributeId() ?>” class=”required-entry super-attribute-select”>
    __(‘Choose an Option…’) ?>

    var spConfig = new Product.Config();

    getChildHtml(‘after’) ?>

    Thanks
    /app/design/frontend/rwd/default/template/catalog/product/view/type/options

  8. Unfortunately its wrong logic. Drop down get reset to first value. But if you remove Choose an option value , it never gets the value of price for first options. Anyways i am noob to magento only 4days. 🙂

  9. in the FTP we don’t have the path, what shall we do?

    /public_html/app/design/frontend/default/default/template/
    The above is the end of the path,
    we don’t have the “catalog” folder or deeper….
    /app/design/frontend/default/your_theme/template/catalog/product/view/type/options/configurable.phtml

    Any advice?

  10. Has anybody managed to get jQuery to select a configurable select, which is then followed by default magento behaviour where following select is populated, please share how?

    I tried this:

    jQuery(‘img’).click(function(){

    var imageAltValue = jQuery(this).attr(“alt”).trim();

    jQuery(‘option:contains(‘ + imageAltValue + ‘)’).each(function(){

    if (jQuery(this).text().trim() == imageAltValue) {
    console.log(this);
    //console.log: [Log] ​BLACK​ (sienna-dress.html, line 5034)

    // works
    jQuery(this).prop(‘selected’, true);
    // doesn’t work
    // jQuery(this).click();
    // jQuery(this).trigger(‘change’);
    return false;
    }
    return true;
    });
    });

  11. Great code, works perfectly!

    Surrounded this section with an IF statement so it only auto-selects it if there is only one option in the list:


    if (dropdown.length <= 2)
    {
    dropdown[0].remove();
    //change selections in dropdowns
    for(index = 0; index < dropdown.length; index++)
    {

    if(dropdown[index].value != "")
    {
    dropdown.selectedIndex = index;

    var element = dropdown;
    var event = 'change';

    //fire events
    if(document.createEventObject)
    {
    var evt = document.createEventObject();
    return element.fireEvent('on'+event,evt)
    }
    else
    {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent(event, true, true );
    return !element.dispatchEvent(evt);
    }
    }
    }
    }

    1. Hi Ross, I can get this to work perfectly as is, but whenever i add your if statement, i end up with this in the console:

      [Error] TypeError: undefined is not an object (evaluating ‘selected.config’)
      reloadPrice (configurable.js, line 280)
      configureElement (configurable.js, line 137)
      configure (configurable.js, line 121)
      (anonymous function) (prototype.js, line 391)
      responder (prototype.js, line 5598)

      I’ve double and triple checked the code. here it is. Any ideas?

          <script type="text/javascript">
              var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
              //we create new function
      
      spConfig.setInitialState = function(dropdown_id)
      {
      
      //select dropdown
      
      var dropdown = $(dropdown_id);
      //remove empty option from dropdown so it is not selectable after initial selection
      if (dropdown.length <= 2)
      {
      dropdown[0].remove();
      //change selections in dropdowns
      for(index = 0; index < dropdown.length; index++)
      {
      
      if(dropdown[index].value != "")
      {
      dropdown.selectedIndex = index;
      
      var element = dropdown;
      var event = 'change';
      
      //fire events
      if(document.createEventObject)
      {
      
      var evt = document.createEventObject();
      return element.fireEvent('on'+event,evt)
      }
      else
      {
      
      var evt = document.createEvent("HTMLEvents");
      evt.initEvent(event, true, true );
      return !element.dispatchEvent(evt);
      }
      }
      }
      }
      };
      
      <?php foreach($_attributes as $_attribute): ?>
      spConfig.setInitialState("attribute<?php echo $_attribute->getAttributeId() ?>")
      <?php endforeach; ?>
          </script>
      <?php endif;?>
  12. It’s working perfectly in Magento 1.9. There are two spaces between “<" and "?" which had to be removed from the code. On the other hand, if you don't see that, you shouldn't be using this snippet.

  13. Thanks, Tom. Unfortunately, this solution didn’t work for me — probably because I’m using CE 1.7 with the Simple Configurable Products extension. There must be some version/extension error. But, the code sure looks nice, and seems like it should work…

    Anyway, here is a bit of code that might help anyone on more recent versions who are also using the SCP extension: http://www.furioustroll.com/2012/07/auto-selecting-a-single-dropdown-option-with-simple-configurable-products-scp/

    (Note: This code works, but it is buggy if users change their selections after configuring the options. I have not yet sorted out this problem.)

  14. @Noel

    What file have you changed in magento 1.7?
    I am looking at the path he specified, and i don’t have a folder called options.

    And the only configurable.phtml file i could find is an empty one saying it was removed at one of the updates.

    Oh an BTW @Tomas Novoselic , thank you for the article and the time you took to help us.

    Yossi

  15. Very nice, thanks for sharing this! Saved me lots of time and great ideas that I could use as a starting point for what I need to do.

    @Matthew: it works fine for me in 1.7.0

  16. @suman Thanks you liked this article that was writen 3 years ago and I’m sorry I couldn’t make it more easy for you. Imagine how hard was for me to write it at the times I couldn’t find any place on internet where I could act smart like you did just now. So, there are 2 courses of action:
    1) Code it yourself and show me how wrong I was
    2) Click here and get updated version of this article.

    Bye bye, I’m glad I could help 🙂

  17. this is a worst post yet ever i seen …..so i request the blog writter dont post such kind of article plzz…this is a artile which make puzzled in magento learning for the begineers….

  18. HI

    I am geting upload HTTP Error in magento when i upload product image in magento
    Can you please provide me a perfect solution

  19. Great post! Is it possible to select a specific option in the dropdown? LIke say you have a size attribute that consists of small, medium, and large. Is is possible to have “medium” selected automatically?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.