How to fix undefined value in stock message on page load?

Topic summary

Main issue: a Shopify product page showed “undefined” in a separate stock message element on page load when using a custom jQuery Pretty Dropdowns variant selector. The goal was to display “In Stock” or “Custom Made” plus timing tags (e.g., 2 Weeks, 4–6 Weeks) both in the dropdown and in a .stock-message div, including products without variants.

Progress and attempts:

  • Initial code relied on click handlers and a variant:change event; stockMessage tied to the selected prettydropdown item was suggested and worked for multi-variant products but not for single (no-variant) products.
  • Edits to the prettydropdowns plugin and conditional logic were tried; edge cases existed where messages were blank but status was still “Custom Made.”

Key fix implemented:

  • For products without variants, read availability and text from hidden data (.hidden-variant option with data-available and data-text).
  • Prevent overrides on variant change by gating the hidden-variant logic to run only when no dropdown exists: $(‘.prettydropdown’).length === 0. This resolved page-load “undefined” and ensured correct updates for both variant and non-variant products.

Outcome: issue resolved; helper asked to mark the solution. An unrelated question about Shopify operating in Cambodia was posted and remains unanswered.

Summarized with AI on February 1. AI used: gpt-5.

Hey! I was messing around some more and added “$(‘.prettydropdown’).length === 0” to the “.hidden-variant” parts and it worked like a charm. Its good to go now!

// update default
    if($.trim($('.prettydropdown li.selected .variant-label').html())=='In Stock' || $('.hidden-variant option').attr('data-available')=='true' && $('.prettydropdown').length === 0) {
      $('.stock-message').html(" In Stock ");    
    } else if($.trim($('.prettydropdown li.selected .variant-label').html())=='Custom Made' && ($.trim($('.prettydropdown li.selected .variant-message').html())!='')) {
      $('.stock-message').html("" + $('.prettydropdown li.selected .variant-label').html() + "" + "" + $('.prettydropdown li.selected .variant-message').html() + "");
    } else if($.trim($('.prettydropdown li.selected .variant-label').html())=='Custom Made' && ($.trim($('.prettydropdown li.selected .variant-message').html())=='')) {
      $('.stock-message').html("" + $('.prettydropdown li.selected .variant-label').html() + "");
    } else if($('.hidden-variant option').attr('data-available')=='false' && $('.hidden-variant option').attr('data-text')=='' && $('.prettydropdown').length === 0) {
      $('.stock-message').html(" Custom Made ");
    } else if($('.hidden-variant option').attr('data-available')=='false' && $('.hidden-variant option').attr('data-text')!='' && $('.prettydropdown').length === 0) {
      $('.stock-message').html(" Custom Made " + "" + $('.hidden-variant option').attr('data-text') + "");
    }
  },500)