Automatic product variant refresh upon selection in drop down menu

Hi,

I have been trying to figure out a way to create an automatic refresh whenever someone selects a variant from the drop down menu on the product page.

I found this code online and added it to the bottom of my theme.js.liquid and it seem to work. However, this only works when someone selects a variant with an item currently in stock. If someone were to select a variant that’s out of stock, this will perform an infinite loop of refreshes to the page. I have provided a screenshot of the code below.

(I am using the simple theme)

If anyone one could help me out with this coding or provide suggestions, I would greatly appreciate it.

Thank you

After searching the internet for a while, I’ve found an alternative solution. While going through many discussions looking for an answer, I noticed that a lot of other people have had the same problem so i’ll post the correct coding here for everyone.

This code should work on all themes.

1. Go to product-template.liquid and paste this code. This code will display the quantity in stock on your product page. Note that this code can be placed anywhere. Depending on where you want your “In stock” quantity message to be displayed.

{% comment %} Inventory tracking on product page {% endcomment %}
            
              {% if current_variant.inventory_management == "shopify" and current_variant.inventory_policy != "continue" %}
              We have {{ current_variant.inventory_quantity }} in stock.
              {% else %}
              This product is available.
              {% endif %}
            

2. If you have variants, you will need to add this code at the bottom of the code provided in 1 (In product-template.liquid). If you don’t have any variants, you can skip this step 2.

{% for variant in product.variants %}

                

                {% endfor %}

3. Next you will have to go to assests > theme.js.liquid and paste this code.

let inventoryHash = document.querySelectorAll('[inventorymanagment]');
      debugger;

Array.from(inventoryHash).forEach(
        (Selectedvariant)=>{

          if(Selectedvariant.dataset.id == variant.id){

I hope this helps everyone out.

Hello,

Thanks for sharing this. I tried it and it display “This product is available” instead of the quantity, could you please tell me how it works ?

Thanks.