How to make configurable options autoselected on Product view page

Featured Image

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.


About Tomas Novoselic

Team Leader/Backend Developer

At Inchoo, Tomas is a Team Leader and Certified Magento Developer who handles Magento modifications at any level. He also works closely with clients on Magento projects of any size and difficulty.

Read more posts by Tomas / Visit Tomas's profile

25 comments

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

  2. 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?

  3. 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?

  4. 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

  5. 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. 🙂

  6. 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?

  7. 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;
    });
    });

  8. 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;?>
  9. 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.

  10. 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.)

  11. @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

  12. 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

  13. @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 🙂

  14. 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….

  15. HI

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

  16. 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>.