Ad

Is There A Way To Get The Variant Id From Serialized Add To Cart Form In Shopify

- 1 answer

currently I am using the standard POST /cart/add.js, Ajax call format, where I set my data: this.$form.serialize. When I console log my serialized Add to Cart form, I see the entire form output with the ID I wish to get the variant id alone however from the form. Is there a method to extract this piece of info?

Ad

Answer

The standard form submit uses an input or select with a name="id" that is the variant ID that is submitted.

So you can target get the variant.id from that input or you can split the serialized output and get the id from there.

You can target it like so for example: document.querySelector('[name="id"]').value

Or if you like to get it from the serialized output you will have to split the string a little in order to get to the name:

var name = this.$form.serialize()
  .map(item => item.split('='))
  .reduce((result, item) => { result[item[0]] = item[1]; return result; }, {})
  .name
Ad
source: stackoverflow.com
Ad