Skip to content

Instantly share code, notes, and snippets.

@JustinSainton
Created June 15, 2015 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinSainton/adb6f99b8e8646acc96f to your computer and use it in GitHub Desktop.
Save JustinSainton/adb6f99b8e8646acc96f to your computer and use it in GitHub Desktop.
(function($){
var hide_fields = function() {
$( '#wpsc-checkout-field-billingcity, #wpsc-checkout-field-billingstate, #wpsc-checkout-field-billingcountry' ).addClass( 'ui-helper-hidden-accessible' );
},
show_fields = function() {
$( '#wpsc-checkout-field-billingcity, #wpsc-checkout-field-billingstate, #wpsc-checkout-field-billingcountry' ).removeClass( 'ui-helper-hidden-accessible' );
},
ping_api = function() {
var $this = $( this ), zip = $this.val();
if ( zip.length < 5 ) {
return;
}
// Note: 'us' here could be set via wp_localize_script(), allowing to work for any of the whitelisted countries available to the API.
// Ensuring that we're always (even on API failure or an invalid response) showing the fields
$.getJSON( 'http://api.zippopotam.us/us/' + zip, function( response ) {
$( '#wpsc-checkout-field-billingcity-control' ).val( response.places[0]['place name'] );
var state = response.places[0]['state'];
$( 'input.wpsc-form-select-region' ).val( state );
$( '#wpsc-checkout-field-billingstate-control option' ).filter(function () { return $(this).html() == state; } ).attr( 'selected', true );
} ).always( show_fields );
};
$(function() {
$( '#wpsc-checkout-field-billingpostcode-control' ).keyup( ping_api );
hide_fields();
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment