0

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.
General Grievance
4531 gold badge7 silver badges12 bronze badges
asked Jul 1, 2024 at 14:46

1 Answer 1

0

You can use this as an example. I implemented it for the default Luma theme, where we have swatches.

enter image description here

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);
});
answered Jul 5, 2024 at 7:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.