Search code examples
jquerywordpresswoocommercedropdownselected

jQuery If dropdown is selected


I am trying to create a jQuery function that should only run if dropdown wc-completed is selected in dropdown on WooCommerce order page. Basically, I want a field to be required before an order can be completed.

I've tried with some if statement but I am not sure on how to tell jQuery it should only run if wc-completed is selected in dropdown menu. Should I use change function instead?

jQuery(document).ready(function($){
  if ($("select#order_status option:selected").val() === "wc-completed" && !$("body").hasClass("post-type-shop_order")) { 
    $("input#wcam-external-link-0").prop('required',true);
  }
});

Solution

  • What you have only runs on page load so yes you should use a change event listener

    jQuery(document).ready(function($) {
    
      $("select#order_status").change(function() {
          if ($(this).val() === "wc-completed" && !$("body").hasClass("post-type-shop_order")) {
            $("input#wcam-external-link-0").prop('required', true);
          }
    
        })
        // optional -- trigger change on page load
        .change()
    
    });