Display Metafield for Variant, Change with New Selection

Highlighted
Explorer
55 0 49

I know similar questions have been asked here and I've gleaned quite a bit from the responses. I think I have all of the pieces, but I'm not assembling them correctly.

 

One of our stores will be reopening for curbside pickup soon. Because of this, I need to be able to display which items have stock in that particular store. I have my metafields setup and know how to get the info from them just fine. What I can't seem to do is get that info to change with the selection of a new variant.

 

From Display product variants metafields I know I have to store the array of metafields in a variable. In my product-form.liquid (an include for the product.liquid in the Turbo theme) I have the following:

 

{% capture meta_data %}
  {% for variant in product.variants %}
  {{ variant.id | json }}: {{ variant.metafields.Channels.chicago_inventory | json }}{% unless forloop.last %},{% endunless %}
{% endfor %}
{% endcapture %}

<script>
var metaData = { {{ meta_data }} }
</script>

<div class="chicago_stock">
{{ variant.metafields.Channels.chicago_inventory }}
</div>

The Namespace of my variant metafields is "Channels" and the field I need is "chicago_inventory". If I display the meta_data array created by the above, it looks like:

 

33462911041581: 3, 33462910320685: 3, 33462896164909: 4, 33462909730861: 3, 7341660667949: 0, 7341660766253: 2

And the initial value does come up properly when the page is loaded.

 

Then, based on that same post, I added to the selectCallback section my apps.js.liquid the following:

$('.chicago_stock', $product).text(metaData[variant.id]);

With that the page wouldn't render, so I also tried:

var chiQty = metaData[variant.id];
$('.chicago_stock', $product).text(chiQty);

Again, no good.

 

To test, I replaced the above with: 

$('.chicago_stock', $product).text(variant.id);

And with that, the variant ID appears on the page where it should and changes properly when I select variants.

 

So I'm assuming I made some stupid mistake on the the Javascript side. I've tried every permutation of the code shown and checked the original post at least ten times, but I admittedly am not familiar with how to pull values from arrays in JS. I've been fighting with this all day and I'm ready to admit that I'm stumped.

 

0 Likes