skip to Main Content

Hey all I am trying to run a function and display a message when a user selects any other country than the US. However, I’m stuck as I can’t even get the select box to log the event on changing of the country. Here’s my code:

function checkIfInternational(e) {
  console.log(e);
}
const shipCountry = document.querySelector("#billing_country"); //Logs the select box

shipCountry.addEventListener("change", checkIfInternational); // listening for the change event

Any ideas on why this is happening? Is Woocommerce preventing JS from running on the page or something?

Edit: JS Fiddle: https://jsfiddle.net/suoc57mg/1/

2

Answers


  1. Assuming that your #billing_country element looks like this:

     <select id="billing_country">
        <option value="US">United State</option>
        <option value="PL">Poland</option>
        <option value="DU">Germany</option>
        <option value="ES">Estonia</option>
        <option value="RU">Mather Russia</option>
     </select>
    

    You can check its value by target’s value of event which you handle in this way.

    document.getElementById("billing_country")?.addEventListener("change", (event) => {
      if (event.target.value !== "US") {
        // not united state :(
      }
    });
    
    Login or Signup to reply.
  2. You need to delegate your event to the document body, otherwise WooCommerce will block your code on checkout.

    As WooCommerce JS code uses already jQuery, try the following:

    jQuery(function($){
        $(document.body).on('change', 'select[name=billing_country]', function(){
            console.log('Country changed: '+$(this).val());
            // Here run your function or code
        });
    });
    

    It should work now.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search