How To

Automatically set postal code when using a Toolset Maps address field

The geocoding service is used to fill the address field with a complete address recognised by the Google Maps API, but the post code is missing and the individual address components are not readily available (e.g. City).

Here is an example of some code that will automatically set a “postcode” custom field when the address field is updated.

The Code assumes a Text Field created with Toolset, named postcode. You need to either enqueue this code where the Field and Address Inputs are used, or if you use it in a CRED Form, add it to the CRED JS Editor.

( function( $ ) {

	$( document ).ready( function(){

		$("input.js-toolset-google-map").on( "geocode:result", function( event, result ){

			var addressComponents = result.address_components,
				postal_code = "";

			$.each( addressComponents, function( index, value ){

				if ( addressComponents[ index ].types[0] == "postal_code" ) {
					postal_code = addressComponents[ index ].short_name;

			} );

			$('input[name="wpcf[postcode]"]').val( postal_code );
		} );

	} );

})( jQuery );