Ad

Anyway Of Using Shopify Metafield In Js.liquid File?

- 1 answer

I want to change the way my product quantity selector works.

At the moment it increments by 1, which is standard. However, all of my products come in different quantities.

So I setup metafields for them with an int value.

So in a normal liquid file I can do {{ product.metafields.qty_incr.qty-incr }} and it displays the value. In this example, 5.

How can I get this to work in my .js.liquid file?

// Add or subtract from the current quantity
  if ($el.hasClass('ajaxcart__qty--plus')) {
    qty += {{ product.metafields.qty_incr.qty-incr }};
  } else {
    qty -= {{ product.metafields.qty_incr.qty-incr }};
    if (qty <= 0) qty = 0;
  }

I did the above, which is not working. Probably a rookie thing here where I can't use liquid in a .js.liquid file.

Ad

Answer

You can create a global js variable in one of your theme files, like so:

<script>const productMetaQtyIncr = {{ product.metafields.qty_incr.qty-incr }}</script>

And then make use of it in the .js file:

// Add or subtract from the current quantity
  if ($el.hasClass('ajaxcart__qty--plus')) {
    qty += productMetaQtyIncr;
  } else {
    qty -= productMetaQtyIncr;
    if (qty <= 0) qty = 0;
  }
Ad
source: stackoverflow.com
Ad