Displaying a variant metafiled based on inventory with callback

Displaying a variant metafiled based on inventory with callback

timetimetime
New Member
5 0 0

I am trying to write some code that does the following:

 

  1. Checks for variant inventory
  2. If the variant inventory is less than or equal to '1', I want to display a variant metafield. In this case, it's
    {{ variant.metafields.my_fields.available_to_order }}
  3. I also need to write a callback in order to show the selected variant's metafield on change.

I have never done this, and I need some guidance. Where does the callback need to go?  I have not written a callback as well. 

 

Replies 3 (3)

NomtechSolution
Astronaut
1245 113 159
  1. Within the event handler function, you can access the currently selected variant using JavaScript. You can retrieve the inventory quantity of the variant using variant.inventory_quantity and compare it to 1.

  2. If the inventory quantity is less than or equal to 1, you can display the variant's metafield using JavaScript or by updating the DOM. For example, if you have an element with an ID "variant-metafield" that you want to update, you can use the following code:

 

document.getElementById('variant-metafield').innerText = variant.metafields.my_fields.available_to_order;

 

Additionally, you can define a callback function that updates the displayed metafield when the variant selection changes. This callback should be attached to the appropriate event, such as the variant selection change event. Here's an example of how you can define a callback function

 

function updateVariantMetafield(variant) {
  if (variant.inventory_quantity <= 1) {
    document.getElementById('variant-metafield').innerText = variant.metafields.my_fields.available_to_order;
  }
}

 

timetimetime
New Member
5 0 0

 

Great! This puts me in the correct direction. I appreciate the time to make this post and to help me out. 

timetimetime
New Member
5 0 0

Below is how I implemented my code.

 

I added a function to the

_onSelectChange: function() {
 ..... }

 

This is the function that I added:

_updateMetafields: function(variant) {
        if (variant.inventory_quantity <= 1) {
          document.getElementById('variant-metafield').innerText = variant.metafields.my_fields.available_to_order;
        }
      },

 

Since we are modifying the DOM, I added a <div> with an ID variant-metafield to the page where I want to output the metafield value.

 

<span id="variant-metafield"> </span>

 

I feel like I am really close. Any help is appreciated.