Super Forms
  • Drag & Drop Form Builder for WordPress
  • Quick start
    • Installation
    • Registration
    • Starting your 15 day trial
    • Purchasing a license
    • Activating a license
    • First time setup
    • Secure file uploads
    • Creating a form
    • Adding form elements
    • Editing elements
    • Publishing your form
    • FAQ
  • Account
    • Dashboard
      • Your Invoices
      • Billing details
      • Your Licenses
      • E-mail Notification
      • Password reset
      • Cancel subscription
  • Common problems
    • Common problems
      • Email delivery problems
        • Why is my form not sending emails?
        • Why are emails going into spam folder/inbox?
      • File upload problems
      • Session expired
      • reCaptcha Troubleshooting – Fix “Not Loading” & Verification Errors
  • Elements
    • Layout elements
      • Column/Grid
      • Multi-part / step
    • Form elements
      • Calculator
      • Signature
      • File upload
      • Datepicker
      • Variable field
      • Dropdown
      • Text field
      • Autosuggest
      • Keywords
      • Radio button
      • Keyword Field
      • Button
      • Audio Recording (microphone)
    • HTML elements
      • Heading
      • HTML (raw)
      • Image
      • TinyMCE
      • Divider
      • Spacer
      • PDF page break
      • Google map element WordPress form
  • Features
    • Basic
      • Confirmations emails
      • Save Form Progression (continue later)
      • Build In Translation System
      • Populate form
      • Popups
      • Import & Export
      • Hide form after submitting
      • Hide or lock out user from your forms
      • Validation
    • Advanced
      • WordPress form with Google sheets dropdown
      • Custom registration form for WordPress
      • Custom login form for WordPress
      • Custom lost password form for WordPress
      • Update current logged in user
      • Secrets
      • Prevent duplicate entries
      • Lock & hide form
      • Password protect
      • Conditional Logic
      • Tags system
      • Address lookup/auto complete
      • Analytics Tracking
      • Conversion Tracking
      • Distance & Duration Calculation
      • If statements
      • Foreach loops
      • E-mail Reminders
      • Variable Fields
      • Form templates - Include elements into other forms - WordPress
      • Transferring data from one form to another
    • Integrations
      • PDF Generator
      • Listings
      • WooCommerce Checkout
        • Fixed price checkout
        • Dynamic price checkout
        • Variable product checkout (variations)
        • Replacing the "Add to cart" on a product page with a form
        • Hiding product from shop and order via custom form
      • PayPal
      • MailChimp
      • Mailster
      • Zapier
      • Stripe (BETA)
      • WooCommerce Instant Order (in progress)
  • Tutorials
    • WordPress Form to Google Sheet Integration
    • GDPR Consent / Terms agreement
    • How to update the plugin
    • Sending emails to specific department for WordPress contact forms
  • Example Forms for WordPress
    • Booking 24 hours ahead of time
  • Developers
    • Code Examples
      • Lookup City by Zipcode for your WordPress form
      • Audio Recording Field
      • Custom API Phone Number Validation for Your WordPress Form
      • Updating WordPress user meta data after login
      • Automatically redirecting to next step after displaying text or a progress bar
      • Dropdown with groups (categories)
      • Prevent form submission based on entered field values
      • Track form submissions with GTM (Google Tag Manager)
      • Tracking Multi-part steps with Google Analytics
      • Tracking Multi-part steps with GTM data layer (dataLayer.push)
      • Track form submissions with third party
      • Compare input field value with database value
      • Insert form data into a custom database table
      • Delete database row after contact entry is deleted in WordPress
      • Limited date availability (slots) for your WordPress booking form
      • Send submitted form data to another site
      • Exclude empty fields from emails
      • Execute custom JS when a column becomes conditionally visible
      • Toolset Plugin: Update comma separated string to Array for meta data saved via Front-end Posting
      • Toolset Plugin: Update file ID to file URL for meta data saved via Front-end Posting
      • Delete uploaded files after email has been send
      • Increase Cookie lifetime for client data such as [Form Progression]
      • Altering cookie secure and httponly parameters
      • Define fake cronjob to clear old client data if cronjob is disabled on your server
      • Define page language attribute based on page ID or URL
      • Define custom headers when doing a POST request
      • Change checkbox/radio layout to vertical on mobile devices
      • Show remaining available form submission allowed
      • Global fields / elements
      • Trim values of fields
      • Re-sending E-mails after editing entries via Listings for WordPress
      • Combine multiple field values into one column on Contact Entries page
      • Altering the attachments for E-mails via PHP code for WordPress
      • Generate dynamic columns with dates based on user selected date from Datepicker element
      • Hide `eye` icon from Listings row based on user role
    • Data storage
    • BETA version
  • Changelog
  • Support
Powered by GitBook
On this page
  1. Developers
  2. Code Examples

Lookup City by Zipcode for your WordPress form

Example JavaScript code and form elements code to lookup a city based on entered zipcode on your WordPress forms. You can change the region by setting the country as parameter if needed.

PreviousCode ExamplesNextAudio Recording Field

Last updated 6 months ago

Even though natively there is no build-in option in Super Forms to lookup a city based on an entered zipcode, you could achieve this relatively easily with some custom JavaScript code and using the Google Geocoding API.

For instance if you enter 7064BW as the zipcode, it will populate the field below that with the corresponding city name e.g. Silvolde.

What you will need are: A Text field named "enter_zipcode" a Text field named "city" and the API key from google. You can change the country name in the API request URL to lookup zipcodes from inside a specific region or country only.

In the example form code below, the city field is set to read only/disabled so that the user cannot alter it themselves. And a validation "Not empty" is applied to display an error in case the entered zipcode didn't match (populate) any city.

If you also wish to only allow your service for specific cities, you could hook into the form submission (PHP side), and return an error whenever the city field doesn't match the list of your cities. Please refer to an example on how to do this (you will need to adjust the code to your liking, but the use-case is the same):

Make sure to set the API key and country in the below code, and make sure this javascript code is loaded on the page where your form is displayed.

<script> 
(function(){ 
    var lookupCityByZipcode = function(zipCode){ 
        var apiKey = 'XXXXX-XXXXX-XXXXX'; // Replace with your actual API key 
        var country = 'Netherlands'; // You can use the full country name or its ISO code (e.g., 'NL') 
        var field = document.querySelector('.super-form input[name="city"]'); 
        fetch('https://maps.googleapis.com/maps/api/geocode/json?address='+zipCode+','+country+'&key='+apiKey).then(response => response.json()).then(data => { 
            if (data.status === 'OK') { 
                var city = data.results[0].address_components.find(component => 
                    component.types.includes('locality') 
                ); 
                if (city) { 
                    console.log('City:', city.long_name); 
                    field.value = city.long_name; 
                } else { 
                    console.log('City not found for this ZIP code.'); 
                    field.value = ''; 
                } 
                SUPER.after_field_change_blur_hook({el: field}); 

            } else { 
                console.error('Error:', data.status); 
            } 
        }).catch(error => console.error('Error fetching data:', error)); 
    }; 
    var debounceTimer, inputField = document.querySelector('.super-form input[name="enter_zipcode"]'); 
    inputField.addEventListener('input', function(event) { 
        // Clear the existing timer if it's still running 
        clearTimeout(debounceTimer); 
        // Set a new timer for 1 second (1000 milliseconds) 
        debounceTimer = setTimeout(function() { 
            // Call the API or function after 1 second of inactivity 
            console.log('API called with value: ' + event.target.value); 
            // Add your API call function here 
            lookupCityByZipcode(event.target.value); 
        }, 1000); 
    }); 

})(); 
</script>

Example form elements code with only two Text fields (for entering a zipcode, and to populate a field with the corresponding city). You can copy paste this code under the [CODE] tab on the form builder page when creating a new form to test this out):

[
    {
        "tag": "text",
        "group": "form_elements",
        "data": {
            "name": "enter_zipcode",
            "email": "Enter zipcode:",
            "placeholder": "Enter zipcode",
            "placeholderFilled": "Enter zipcode",
            "type": "text",
            "validation": "empty",
            "error": "Please enter your zipcode",
            "address_normalize": "",
            "exclude": "2",
            "exclude_entry": "true",
            "icon": "user"
        }
    },
    {
        "tag": "text",
        "group": "form_elements",
        "data": {
            "name": "city",
            "email": "City:",
            "placeholder": "Your Full Name",
            "placeholderFilled": "Name",
            "type": "text",
            "validation": "empty",
            "address_normalize": "",
            "disabled": "1",
            "readonly": "true",
            "autocomplete": "true",
            "icon": "user"
        }
    }
]
https://docs.super-forms.com/developers/code-examples/compare-input-field-value-with-database-value