2

OK, so I have a product landing page with no options to load specific product options, which creates a big problem when linking ecommerce sites with a product feed for specific sizes and their respective prices, weights, etc. So I have this landing page for a certain product, and I need to load the specific options on document.ready based on URI params. I want to pass "size" and trigger a click on Twin, Full, Queen, or King based on the query string. Here's an example of what I'm looking at: mattress product page. I'm not anywhere near to parsing and handling the parameters, though.

My problem is I jumped into HTML, CSS, Javascript, and jQuery all at once, and I'm not 100% as to what I'm doing with this. Right now I'm just trying to determine on which object I should be triggering the click. All of the tutorials I've found have a name to reference, as in this example jQuery not triggering on radio button change. I've tried a bunch of combinations of the attempts below in chrome's developer console, but it doesn't seem to include the jQuery scripts referenced in the header.

If someone could explain to be which class or selector would be the object I should be working with, how it's manipulated in the script, and how it would appear in the DOM, I would really appreciate it. Also, if anyone has any reference books to recommend, please do so.

Should it be something like

$(".ProductOptionList option:first").click();

or

$(".VariationSelect:eq(*index of array of selections I want to click*)").something? attr()? var()? html()? 

Here are the (hopefully) relevant sections of javascript

from product.js:

$(document).ready(function() {

...

// disable all but the first variation box
$(".VariationSelect:gt(0)").attr('disabled', 'disabled');

var prodVarSelectionMap = {}
$(".VariationSelect").change(function() {
    // cache a map of currently selected values.
    var mapIndex = 0;
    $('.VariationSelect').each(function() {
        prodVarSelectionMap[mapIndex] = this.value;
        mapIndex++;
    });

    // get the index of this select
    var index = $('.VariationSelect').index($(this));

    // deselected an option, disable all select's greater than this
    if (this.selectedIndex == 0) {
        $('.VariationSelect:gt(' + index + ')').attr('disabled', 'disabled')
        updateSelectedVariation($('body'));
        return;
    }
    else {
        // disable selects greater than the next
        $('.VariationSelect:gt(' + (index + 1) + ')').attr('disabled', 'disabled')
    }

    //serialize the options of the variation selects
    var optionIds = '';
    $('.VariationSelect:lt(' + (index + 1) + ')').each(function() {
        if (optionIds != '') {
            optionIds += ',';
        }

        optionIds += $(this).val();
    });
    // request values for this option
    $.getJSON(
        '/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionIds,
        function(data) {
            // were options returned?
            if (data.hasOptions) {
                // load options into the next select, disable and focus it
                $('.VariationSelect:eq(' + (index + 1) + ') option:gt(0)').remove();
                $('.VariationSelect:eq(' + (index + 1) + ')').append(data.options).attr('disabled', false).focus();

                // auto select previously selected option, and cascade down, if possible
                var preVal = prodVarSelectionMap[(index + 1)];
                if (preVal != '') {
                    var preOption = $('.VariationSelect:eq(' + (index + 1) + ') option[value=' +preVal+']');
                    if (preOption) {
                        preOption.attr('selected', true);
                        $('.VariationSelect:eq(' + (index + 1) + ')').trigger('change');
                    }
                }
            }
            else if (data.comboFound) { // was a combination found instead?
                // display price, image etc
                updateSelectedVariation($('body'), data, data.combinationid);
            }
        }
    );
});

//radio button variations
$('.ProductOptionList input[type=radio]').click(function() {
    //current selected option id
    var optionId = $(this).val();
    // request values for this option
    $.getJSON(
        '/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionId,
        function(data) {
            if (!data) {
                return;
            }

            if (data.comboFound) { // was a combination found instead?
                // display price, image etc
                updateSelectedVariation($('body'), data, data.combinationid);
            }
        }
    );
});

from product.functions.js:

/* Product Variations */
var baseProduct = {};

function updateSelectedVariation(parent, variation, id) {
    if(typeof(parent) == 'undefined') {
        parent = $('body');
    }
    else {
        parent = $(parent);
    }

    if (typeof id == 'undefined') {
        id = '';
    }

    if(typeof(baseProduct.price) == 'undefined') {
        if($('.AddCartButton', parent).css('display') == "none") {
            var cartVisible = false;
        }
        else {
            var cartVisible = true;
        }

        var stockMessageVisible = false;
        if($('.OutOfStockMessage', parent).css('display') != 'none') {
            stockMessageVisible = true;
        }

        var price;
        $('.VariationProductPrice', parent).each(function(){
            var $$ = $(this);
            if ($$.is('input')) {
                price = $$.val();
            } else {
                price = $$.html();
            }
        });

        baseProduct = {
            saveAmount: $.trim($('.YouSaveAmount', parent).html()),
            price: $.trim(price),
            sku: $.trim($('.VariationProductSKU', parent).html()),
            weight: $.trim($('.VariationProductWeight', parent).html()),
            thumb: $.trim($('.ProductThumbImage img', parent).attr('src')),
            cartButton: cartVisible,
            stockMessage: stockMessageVisible,
            stockMessageText: $('.OutOfStockMessage', parent).html()
        };

    }

// Show the defaults again
    if(typeof(variation) == 'undefined') {
        $('.WishListVariationId', parent).val('');
        $('.CartVariationId', parent).val('');
        if(baseProduct.saveAmount) {
            $('.YouSave', parent).show();
            $('.YouSaveAmount').html(baseProduct.saveAmount);
        } else {
            $('.YouSave', parent).hide();
        } 
        $('.VariationProductPrice', parent).each(function(){
            var $$ = $(this);
            if ($$.is('input')) {
                $$.val(baseProduct.price);
            } else {
                $$.html(baseProduct.price);
            }
        });
        $('.VariationProductSKU', parent).html(baseProduct.sku);
        $('.VariationProductWeight', parent).html(baseProduct.weight);
        $('.ProductThumbImage img', parent).attr('src', baseProduct.thumb);
        $(parent).attr('currentVariation', '');
        $(parent).attr('currentVariationImage', '')
        if(baseProduct.sku == '') {
            $('.ProductSKU', parent).hide();
        }
        if(baseProduct.cartButton) {
            $('.AddCartButton', parent).show();
            if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
                $('.QuantityInput', parent).show();
            }
        }

        if(baseProduct.stockMessage) {
            $('.OutOfStockMessage', parent)
                .show()
                .html(baseProduct.stockMessageText)
            ;
        }
        else {
            $('.OutOfStockMessage').hide();
        }

        $('.InventoryLevel', parent).hide();
    }
// Otherwise, showing a specific variation
    else {
        $('.WishListVariationId', parent).val(id);
        $('.CartVariationId', parent).val(id);

        $('.VariationProductPrice', parent).each(function(){
            var $$ = $(this),
                price = baseProduct.price;
                price = '777';

            if (variation.price !== undefined) {
                price = variation.price;
            }

            if ($$.is('input')) {
                $$.val(price.replace(/[^0-9\.,]/g, ''));
            } else {
                $$.html(price);
            }
        });

        if(variation.sku != '') {
            $('.VariationProductSKU', parent).html(variation.sku);
            $('.ProductSKU', parent).show();
        }
        else {
            $('.VariationProductSKU', parent).html(baseProduct.sku);
            if(baseProduct.sku) {
                $('.ProductSKU', parent).show();
            }
            else {
                $('.ProductSKU', parent).hide();
            }
        }
        $('.VariationProductWeight', parent).html(variation.weight);
        if(variation.instock == true) {
            $('.AddCartButton', parent).show();
            if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
                $('.QuantityInput', parent).show();
            }
            $('.OutOfStockMessage', parent).hide();
        }
        else {
            $('.AddCartButton, .QuantityInput', parent).hide();
            $('.OutOfStockMessage', parent).html(lang.VariationSoldOutMessage);
            $('.OutOfStockMessage', parent).show();
        }
        if(variation.thumb != '') {
            ShowVariationThumb = true;
            $('.ProductThumbImage img', parent).attr('src', variation.thumb);
            $(parent).attr('currentVariation', id);
            $(parent).attr('currentVariationImage', variation.image);

            $('.ProductThumbImage a').attr("href", variation.image);
        }
        else {
            $('.ProductThumbImage img', parent).attr('src', baseProduct.thumb);
            $(parent).attr('currentVariation', '');
            $(parent).attr('currentVariationImage', '')
        }
        if(variation.stock && parseInt(variation.stock)) {
            $('.InventoryLevel', parent).show();
            $('.VariationProductInventory', parent).html(variation.stock);
        }
        else {
            $('.InventoryLevel', parent).hide();
        }
        if(variation.saveAmount) {
            $('.YouSave', parent).show();
            $('.YouSaveAmount').html(variation.saveAmount);
            $('.RetailPrice').show();
        } else {
            $('.YouSave', parent).hide();
            $('.RetailPrice').hide();
        }
    }
}


function GenerateProductTabs()
{
    var ActiveTab = 'Active';
    var ProductTab = '';
    var TabNames = new Array();

    TabNames['ProductDescription'] = lang.Description;
    TabNames['ProductWarranty'] = lang.Warranty;
    TabNames['ProductOtherDetails'] = lang.OtherDetails;
    TabNames['SimilarProductsByTag'] = lang.ProductTags;
    TabNames['ProductByCategory'] = lang.SimilarProducts;
    TabNames['ProductReviews'] = lang.Reviews;
    TabNames['ProductVideos'] = lang.ProductVideos;
    TabNames['SimilarProductsByCustomerViews'] = lang.SimilarProductsByCustomerViews;
    $('.Content .Moveable').each (function() {
        if (this.id == 'ProductBreadcrumb' ||
            this.id == 'ProductDetails' ||
            $(this).html() == '' ||
            !TabNames[this.id]
            ) {
            return;
        }

        TabName = TabNames[this.id];
        ProductTab += '<li id="'+this.id+'_Tab" class="'+ActiveTab+'"><a    onclick="ActiveProductTab(\''+this.id+'_Tab\'); return false;" href="#">'+TabName+'</a></li>';

        if (ActiveTab == '')
        {
        $('#'+this.id).hide();
        }
        $('#'+this.id).removeClass('Moveable');
        ActiveTab = "";
    });

    if (ProductTab != '')
    {
        $('#ProductTabsList').html(ProductTab);
    }
}

this is from the dev console:

<div class="productAttributeList" style="">
            <div class="productAttributeRow productAttributeConfigurablePickListSet productAttributeRuleCondition" id="a02034dba575c64f27ad8724b46b9d4d">
    <div class="productAttributeLabel">
        <label for="93a2b37dabd1fe9deae210d2ac0a6b80">
                            <span class="required">*</span>
                        <span class="name">
            Mattress Size:          </span>
        </label>
     </div>
     <div class="productAttributeValue">

 <div class="productOptionViewRectangle">
    <ul class="list-horizontal">
                        <li class="option selectedValue">
        <label for="a224072f64cc4ad05f0cabb0ec516c7d">
            <input type="radio" class="validation" name="attribute[251]" value="2" id="a224072f64cc4ad05f0cabb0ec516c7d">
            <span class="name">TwinXL</span>
        </label>
    </li>

                        <li class="option">
        <label for="b0204680fe57cec48dab9edc28a34a7d">
            <input type="radio" class="validation" name="attribute[251]" value="3" id="b0204680fe57cec48dab9edc28a34a7d">
            <span class="name">Full</span>
        </label>
    </li>

                        <li class="option">
        <label for="83f68b784f33ebf11dbde126b9a9fc97">
            <input type="radio" class="validation" name="attribute[251]" value="4" id="83f68b784f33ebf11dbde126b9a9fc97">
            <span class="name">Queen</span>
        </label>
    </li>

                        <li class="option">
        <label for="fe4651efe956ed8fb3f9b0635e35322d">
            <input type="radio" class="validation" name="attribute[251]" value="5" id="fe4651efe956ed8fb3f9b0635e35322d">
            <span class="name">King</span>
        </label>
    </li>

                        <li class="option">
         <label for="c6c1071e4bc6a5edfd0524dd8ad042c2">
            <input type="radio" class="validation" name="attribute[251]" value="6" id="c6c1071e4bc6a5edfd0524dd8ad042c2">
            <span class="name">California King</span>
        </label>
    </li>

                    </ul>
</div>
    </div>
    <div class="cf"></div>
</div>
<div class="productAttributeRow productAttributeConfigurablePickListSet productAttributeRuleCondition" id="668978c662c62cf05439063491e89dc9">
    <div class="productAttributeLabel">
        <label for="e58baa61c3f97085e9c2e7742dbf1595">
                            <span class="required">*</span>
                        <span class="name">
                Add Box Spring Foundation:          </span>
        </label>
    </div>
    <div class="productAttributeValue">
    <div class="productOptionViewSelect">
    <div class="selector fixedWidth" id="uniform-e58baa61c3f97085e9c2e7742dbf1595"><span style="-webkit-user-select: none;">Mattress Only</span><select class="validation" id="e58baa61c3f97085e9c2e7742dbf1595" name="attribute[1123]">
         <option value="">
                            -- Please Choose an Option --                       </option>

                    <option value="36" selected="selected">Mattress Only</option>
                    <option value="37">Standard Height (9")</option>
                    <option value="38">Low Profile (5")</option>
            </select></div>
</div>  </div>
    <div class="cf"></div>
</div>
<div class="productAttributeRow productAttributeConfigurablePickListSet" id="11d522cf8329ffc8cb74e3c2934a9a3d">
    <div class="productAttributeLabel">
        <label for="fbde0c153d55c827e931b260145f3442">
                        <span class="name">
                Add Premium Bed Frame:          </span>
        </label>
    </div>
    <div class="productAttributeValue">
    <div class="productOptionViewSelect">
    <div class="selector fixedWidth" id="uniform-fbde0c153d55c827e931b260145f3442"><span style="-webkit-user-select: none;">
                            -- None --
                    </span><select class="validation" id="fbde0c153d55c827e931b260145f3442" name="attribute[1136]">
        <option value="" selected="selected">
                            -- None --
                    </option>

                    <option value="35">Add Bed Frame</option>
            </select></div>
</div>  </div>
    <div class="cf"></div>
</div>
<div class="productAttributeRow productAttributeConfigurablePickListSet" id="d8e2352c51c3bff1643b103c8e92f5bd">
    <div class="productAttributeLabel">
        <label for="96ce2d73c8b6a02a747111a1b793442c">
                        <span class="name">
                Add Premium Mattress Protector:         </span>
        </label>
    </div>
    <div class="productAttributeValue">
    <div class="productOptionViewSelect">
    <div class="selector fixedWidth" id="uniform-96ce2d73c8b6a02a747111a1b793442c"><span style="-webkit-user-select: none;">
                            -- None --
                    </span><select class="validation"  id="96ce2d73c8b6a02a747111a1b793442c" name="attribute[1149]">
        <option value="" selected="selected">
                            -- None --
                    </option>

                    <option value="34">Add Mattress Protector</option>
            </select></div>
</div>  </div
Community
  • 1
  • 1

2 Answers2

0

If you're working with radios and attempting to deselect all and then select a specific one you need two things: name and a unique identifier. Use the name to deselect all the ones in that group, and use the ID to select the one you need. If you don't have ID, you could always use value. Or, if you just want to select the first one available, use the name to get the radio/check group, and use the .first() filter to get the first matched element.

Info on selectors: http://api.jquery.com/category/selectors/

How to use the attribute selector for the name or value: http://api.jquery.com/attribute-equals-selector/

How to get via ID: http://api.jquery.com/id-selector/

Triggering a "click" event will also trigger any events bound to click or change on an element. If you need that, then trigger the click like you're trying. If you just need to toggle the check state, though, you can use this method: How to uncheck a radio button?

As an edit after your comment: It's nice to see you using some core JavaScript for this. When I work with forms, I like to use a combination with jQuery. Something like:

$('[name="attribute[251]"]').each(function() {
    this.checked = false;
});

or

$('#b0204680fe57cec48dab9edc28a34a7d')[0].checked = true;

Everyone has their own preference on this. This is just an example approach.

Community
  • 1
  • 1
Daved
  • 2,082
  • 1
  • 18
  • 23
  • Thanks, I realized I wasn't in the right tab when attempting to use the javascript console. Within the console, I got var listItem = document.getElementById( "73d6c54930a1a17646aab1f956a1f1cb" ); and listItem.click(); to do exactly what I wanted. I haven't looked to where the id is created so that I could do this within the script itself – Peter Anania Mar 05 '15 at 22:25
  • Edit: the "73d6c54930a1a17646aab1f956a1f1cb" id was the id of the Full size selection on the page I was working on, and would be "b0204680fe57cec48dab9edc28a34a7d" in the example originally given above. – Peter Anania Mar 05 '15 at 22:32
0

Default Select first variation: Add this in Product.html ( Bigcommerce Theme file ) For Size:

$(document).ready(function() {
    $(".productOptionViewRectangle ul").each(function() {
        $(this).children("li").first().addClass("selectedValue");
        $("li.selectedValue input.validation").attr('checked',true);
    });
});

For Color Swatch:

$(document).ready(function() {
    $(".productOptionPickListSwatch ul").each(function() {
        $(this).children("li").first().addClass("selectedValue");
        $("li.selectedValue input.validation").attr('checked',true);
    });
});