Automatically fill city field when entering zip code

Hi,

I want my form to fill the city field according to the entered zip code automatically.

I've found this code (for a totally different plugin, just an example): 
       <script>
    $('#PLZ').bind('keyup change', function (e) {
        if ($(this).val().length > 4) {
            var ort = $('#Ort');
            $.getJSON('https://secure.geonames.org/postalCodeLookupJSON?&country=DE&callback=?', { postalcode: this.value }, function (response) {
            if (response && response.postalcodes.length &username=username& response.postalcodes[0].placeName) {
                ort.val(response.postalcodes[0].placeName);
            }
          })
        } else {
            $('#Ort').val('');
        }
        });
    </script>

I have no idea how to rewrite this code for Gravity. After two days of reading documentation and searching the internet I’m pretty desperate. How do I get Gravity to look up the zip code at https://secure.geonames.org BEFORE saving the form and return the correct city name into the city field?

Would be grateful for any help / hint / idea!

2 Likes

Hi! I would like to help out with this. I will look at it later today.

Art Smith

2 Likes

That would be such a gift, thank you so much :blush:

If you have the city-to-zipcode table defined somewhere as a Wordpress database table, you can use Gravity Perks Populate Anything (GPPA) to dynamically populate the city field based on a query lookup defined within that field in your gravity forms. The city field can also have Conditional Logic to be displayed only when the zipcode is not blank. And also can be defined as “Read Only” with Gravity Perks so users cannot change the city unless they input a proper zip code.

Hi Rabih,
thank you so much for your suggestion! :bouquet: I’ve thought about something like that at first. Unfortunately it won’t meet my needs. ZIP codes should not be defined in a database table but looked up at geonames.org. So I need a way to enter the ZIP code WHILE filling out the form (before saving / submitting) automatically at geonames and to return the matching city name to the city field.
Sorry, my English is not perfect but I hope you understand what I mean.