Custom JS not quite working on WooCommerce checkout page

Hi,

I trying to add / remove some html depending on the selection chosen in the dropdown box on the WooCommerce checkout page - basically if it’s the UK then phone number not required but it is required for all other countries. I’ve got the PHP side working via WooCommerce Hooks but struggling with the javascript. So far I have

jQuery( document ).ajaxComplete(function() {
	jQuery( ":input.country_to_state" ).change(function() {
		if (jQuery("#select2-billing_country-container").text()==="United Kingdom (UK)") {
			alert("UK selected")
			//jQuery("#billing_phone_field > label > abbr").hide();
		} 
		else 
		{
			alert("Non UK Country Selected")
			//jQuery("#billing_phone_field > label > abbr").show();			
		}
	})
  });
  
  //almost there but not 'clearing' if selecting one after another

The alerts are coming up OK however if I keep testing and selecting different countries then I have to click OK more and more times e.g. if I’ve selected 5 countries I’d have to click OK 5 times. Also if I comment out the alerts and uncomment the parts I want to show / hide that doesn’t seem to work - they do work OK in the command line - I’m hoping it’s linked to the reason it needs clicking too many times…

Thanks

Andrew

I think that you have found that alerts are not beneficial when it comes to debugging code.

I recommend that you use the development console instead. Here’s some instructions on how to open the developer console

You can replace those alerts with console log statements instead:

// alert("UK selected")
console.log("UK selected");

That way, the information appears in the console, and you don’t have the annoyance of clicking alert buttons all the time.

Thanks Paul,

I think I’d overcomplicated it and confused myself quite a lot with that… someone on the WP WooCommerce kindly corrected the code with the javascript part shown below. Thanks for the tip though I’ll put that to good use whilst getting learning JS in earnest :slight_smile:

<script>
jQuery( '#billing_country' ).change( function () {
var customercountry = jQuery('#billing_country').val();
if (customercountry == "GB") {
jQuery("#billing_phone_field > label > abbr").hide();
}
else {
jQuery("#billing_phone_field > label > abbr").show();
}
});
</script>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.