How to get the SELECTED variant value?

Solved
MelonCiroc
New Member
4 0 0

Hello, I'm trying to get the value of the currently selected Product Variants. 

Lets say I have the following, if productType is "Charger" instead of "Phone", I want the "Color" label to become "Voltage".
How do I get the selected value of the Option 1 (productType), and render the 2nd option label accordingly?

MelonCiroc_0-1608329189735.png

 

I would ideally like to do this without deep linking, so is there some kind of JS/Jquery to get the is-selected value?  Thanks!

 



0 Likes

This is an accepted solution.

This is a very broad question - for each theme it will be in a different way. 

Regardless of the swatches, it's very likely that the variant ID will be changed with a select html element, so you got to add an addEventListener to it to listen for changes and, whenever it changes, you do an API call to your current product and get the variant data. 

This is not going to work on every theme, but I use the following functions and adapt them to whatever them I'm using. Because of my job I don't have enough time to dissect the code, but it should be more than a good enough starting point, you'll need javascript knowledge to move forward which I assume you do have already. 

async function _getCurrentProduct() {
  const product = document.querySelector(`script[id*='ProductJson']`);

  if (product) {
    return JSON.parse(product.innerHTML);
  }

  let url;

  url = `https://${window.location.host + window.location.pathname}.json`;

  return new Promise(async (resolve, reject) => {
    let response = await fetch(url);

    let { product } = await response.json();

    window.ezfy_product = product;

    resolve(product);
  });
}

async function _getCurrentVariant() {
  const product = await _getCurrentProduct();
  const variant = await _getVariantID(product);
  return variant;
}

function _getVariantID(product) {
  const options = document.querySelector(`.product-form__variants`);

  const currentVariantID = parseInt(
    options.selectedOptions[0].value.trim().toLowerCase(),
  );

  const variant = product.variants.filter((e) => e.id === currentVariantID)[0];

  return variant;
}

async function currentVariant() {
  var variant = await _getCurrentVariant();
  console.log(variant);
}

currentVariant();
◦ Product page slider & thumbnails with swiping for free themes: Minimal | Debut | Brooklyn | Supply
◦ Replace apps with simple copy/paste code snippets. Examples clicking here.
0 Likes