Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(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