I have a product with custom options like Color and Size.
When users visit a product page with a URL like https://example.com/product.html?color=Red&size=Small, I want the Color option to be preselected as "Red" and the Size option as "Small" automatically.
I need guidance on how to:
- Retrieve the values from the URL parameters (color and size).
- Use JavaScript/jQuery to preselect these options dynamically on page load.
- Ensure that the preselected options reflect in the dropdown selects or radio buttons on the Magento 2 product page.
1 Answer 1
You can use this as an example. I implemented it for the default Luma theme, where we have swatches.
jQuery(document).ready(function() {
jQuery.urlParam = function(name) {
var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(window.location.href);
return results ? decodeURIComponent(results[1]) : null;
}
function selectAttribute(attribute) {
var value = jQuery.urlParam(attribute);
if (value) {
var el = jQuery("[data-attribute-code='" + attribute + "']").find(".swatch-attribute-options").find("[data-option-label='" + value + "']");
if (!el.hasClass("selected") && !el.hasClass("disabled")) {
el.trigger('click');
}
return el;
}
return null;
}
var elColor = selectAttribute('color');
var elSize = selectAttribute('size');
console.log('Default Select', elColor, elSize);
});
Explore related questions
See similar questions with these tags.