Address Autocomplete JavaScript Solution
The Address Autocomplete JavaScript Solution is a lightweight JavaScript tool that makes it easy to add Smarty’s US Address Autocomplete and/or International Address Autocomplete to any web form that collects address information with minimal setup.
As users begin typing an address, the plugin displays suggested addresses in a dropdown list. When the user selects a suggestion, the plugin automatically fills in the remaining address fields.
*Note: If you’re a developer looking for full technical documentation and advanced configuration options, you can visit the npm README. This guide provides a simplified overview of the plugin.
Contents
- Quick start
- Field definitions
- Advanced options
- Additional considerations for international autocomplete setup
Quick start
The Address Autocomplete JavaScript Solution is designed to work with almost any address form. We’ll help you get started:
Locate the form you want to enhance with the plugin.
If you don’t already have a form, you can create one like the example below:
<form> <input type="text" id="street" placeholder="Start typing an address..." /> <input type="text" id="secondary" /> <input type="text" id="city" /> <input type="text" id="state" /> <input type="text" id="zipcode" /> </form>Each address-related field needs to be identified with CSS selectors, such as IDs or class names. In this example, the fields use the IDs
street,city,state, andzipcode.Initialize the Address Autocomplete JavaScript Solution with this short JavaScript snippet.
<script src="https://cdn.jsdelivr.net/npm/smarty-address/dist/smarty-address.iife.js"> </script> <script type="module"> const autocomplete = await SmartyAddress.create({ embeddedKey: "your-smarty-embedded-key", streetSelector: "#street", secondarySelector: "#secondary", citySelector: "#city", stateSelector: "#state", zipcodeSelector: "#zipcode", }); </script>*Be sure to replace the
embeddedKeyand selector values with your own.You can find or create your embedded key in your Smarty account under Account → API Keys.
What you’re doing by initializing the plugin is allowing the fields to automatically populate when the user selects the address, such as street, city, state, and ZIP Code. If the selected address includes secondary address options such as an apartment or suite, the plugin can prompt the user to select the correct unit.
Implement the clean-up function.
When you no longer need an autocomplete instance (for example, when navigating away in a single-page application), call
destroy()to clean up event listeners and DOM elements to prevent memory leaks:const autocomplete = await SmartyAddress.create({ embeddedKey: "your-key", streetSelector: "#street", }); // Later, when done with the autocomplete: autocomplete.destroy();
Field definitions
Required options
These options are required for the Address Autocomplete JavaScript Solution to work.
| Option | Type | Description |
|---|---|---|
| embeddedKey | string | Your Smarty embedded key |
| streetSelector | string | CSS selector for street address field (also used as the autocomplete input unless searchInputSelector is provided) |
Form field selectors
These selectors define where the selected address data will populate.
| Option | Type | Description |
|---|---|---|
| countrySelector | string | CSS selector for a form field whose value supplies the country at lookup time. Takes precedence over country when set. *Note: The tool will default to “USA” until the country is set. |
| searchInputSelector | string | CSS selector for the autocomplete input. Only needed when the autocomplete input is a different element from where the street address will be populated (e.g., a unified search field that populates separate street/city/state fields) |
| secondarySelector | string | CSS selector for secondary address (apt, suite, etc.) |
| citySelector | string | CSS selector for the "city" field |
| stateSelector | string | CSS selector for the "state" field |
| zipcodeSelector | string | CSS selector for the "ZIP Code" field |
International-specific field selectors For international forms, you may prefer the equivalent aliases, which map to the same fields but use region-neutral names. This isn’t required for full functionality of the JavaScript solution, so setting these selectors is optional and based solely on your preferences. | ||
| countrySelector | string | CSS selector for a form field whose value supplies the country at lookup time. Takes precedence over country when set. *Note: The tool will default to “USA” until the country is set. |
| localitySelector | string | CSS selector for the "local area" field |
| administrativeAreaSelector | string | CSS selector for the "administrative area" field |
| postalCodeSelector | string | CSS selector for the "postal code" field |
Advanced options
The Address Autocomplete JavaScript Solution can be customized to work with many different address form layouts. Use the required options to get started, then add optional selectors and filters to match your form layout and desired user experience.
This documentation provides a simplified overview of the most common configuration options. For a complete list of configuration settings, see our npm README.
Multiple instances
You can create multiple instances of the Address Autocomplete JavaScript Solution on the same page. This is useful for pages that contain multiple address forms, such as separate billing and shipping address sections.
Each instance must be initialized with selectors that point to the fields in the corresponding form. Here’s an example of how this can be done.
<script src="https://cdn.jsdelivr.net/npm/smarty-address/dist/smarty-address.iife.js"></script>
<script type="module">
const shippingAutocomplete = await SmartyAddress.create({
embeddedKey: "your-smarty-embedded-key",
streetSelector: "#shipping-street",
citySelector: "#shipping-city",
stateSelector: "#shipping-state",
zipcodeSelector: "#shipping-zipcode",
});
const billingAutocomplete = await SmartyAddress.create({
embeddedKey: "your-smarty-embedded-key",
streetSelector: "#billing-street",
citySelector: "#billing-city",
stateSelector: "#billing-state",
zipcodeSelector: "#billing-zipcode",
});
</script>Each plugin instance operates independently and only fills the fields specified in its configuration.
API options
The plugin includes configuration options that control how autocomplete suggestions are requested and filtered.
These options are passed when the plugin is initialized.
| Name | Type | Default value | Description |
|---|---|---|---|
country | string | USA | Static ISO 3166-1 alpha-2 or alpha-3 country code (e.g., "US", "USA", "GBR"). Defaults to "USA" if neither this nor countrySelector is set. |
maxResults | integer | 10 | Maximum number of address suggestions to return; range [1, 10]. |
includeOnlyCities | string | (empty) | Limit the results to only those cities/localities listed, as well as those in includeOnlyStates or includeOnlyAdministrativeAreas.IMPORTANT: This field must contain a state/administrative area after the list of cities/localities as shown in the example. Another important note is that you should NOT list a state mentioned within this field in the includeOnlyStates or includeOnlyAdministrativeAreas field as it takes precedence over this field.Example: DENVER,AURORA,CO;OMAHA,NE See filtering for more information. |
includeOnlyZipCodes | string | (empty) | Limit the results to only those ZIP Codes/postal codes listed. When this parameter is used, no other cities, states parameters can be used.Note: When using this parameter, the preferGeolocation parameter must NOT be set to city or locality.Example: 90210;06504 See filtering for more information. |
preferCities or preferLocalities | string | (empty) | Display suggestions with the listed cities/localities and states/administrative areas at the top of the suggestion list, as well as those listed in preferStates or preferAdministrativeAreas. Example: DENVER,AURORA,CO;OMAHA,NE See preferencing for more information. |
preferStates or preferAdministrativeAreas | string | (empty) | Display suggestions with the listed states/administrative areas at the top of the suggestion list, as well as those listed in preferCities or preferLocalities.Examples: UT;ID;MT See preferencing for more information. |
preferZipCodes or preferPostalCodes | string | (empty) | Display suggestions with the listed ZIP Codes/postal codes at the top of the suggestion list. When this parameter is used, no other cities/localities or states/administrative areas parameters can be used. Note: When using this parameter, the preferGeolocation parameter must NOT be set to city.See preferencing for more information. |
US Address Autocomplete specific API options These options won’t return a response for calls to the International Address Autocomplete API. | |||
source | string | postal | Include results from alternate data sources. Allowed values are:all - will include non-postal addresses in the resultspostal - will limit the results to postal addresses onlyIf this parameter is used, an additional field named source will be returned for each result, which is either postal for postal addresses, or other if the address is from an alternate data source. |
preferRatio | integer | 100 | Specifies the percentage of address suggestions that should be preferred and will appear at the top of the suggestion list. Expressed as an integer value, range [0, 100]. See preferencing for more information. |
excludeStates | string | (empty) | Exclude the following states/administrative areas from the results. When this parameter is used, no other include parameters may be used.Note: The preferGeolocation parameter MUST be set to none if the customer's current location is in a state/administrative area specified in this parameter; otherwise the customer will see addresses from their current location.Example: SD;ND;MT See filtering for more information. |
includeOnlyStates | string | (empty) | Limit the results to only those states/administrative areas listed, as well as those listed in includeOnlyCities or includeOnlyLocalities.IMPORTANT: If a state/administrative area is mentioned in the includeOnlyCities or includeOnlyLocalities fields, you should NOT include that same state/administrative area in this field as it will take precedence. Examples: UT;ID;MT or CONTIGUOUS or ALLSTATES See filtering for more information. |
preferGeolocation | string | city | If omitted or set to city, it uses the sender's IP address (IPv4 only) to determine location, then automatically adds the city and state to the preferCities value. This parameter takes precedence over other include or exclude parameters meaning that if it is not set to none, you may see addresses from the customer's area when you may not desire it.Acceptable values are: empty string (which defaults to city), none, or city.Notes: 1. If any zipCodes parameters are used, this parameter must NOT be set to city)2. If the request to the Autocomplete Pro API goes through a proxy, you will need to set an X-Forwarded-For header specifying the user's IP address. |
For the full list of API options and advanced configuration details, see the npm README.
Themes
The Address Autocomplete JavaScript Solution can be styled to match your site’s design. Themes are configured during plugin initialization. Four built-in themes are available to choose from:
// Default theme (adapts to input colors)
const autocomplete = await SmartyAddress.create({
theme: SmartyAddress.themes.default,
// ...
});
// Light theme
const autocomplete = await SmartyAddress.create({
theme: SmartyAddress.themes.light,
// ...
});
// Dark theme
const autocomplete = await SmartyAddress.create({
theme: SmartyAddress.themes.dark,
// ...
});
// No styling (bring your own CSS)
const autocomplete = await SmartyAddress.create({
theme: SmartyAddress.themes.none,
// ...
});Additional considerations for international autocomplete setup
By default, the Address Autocomplete JavaScript Solution is configured for US addresses. If you want to collect international addresses, here are the changes you'll need to make to your setup.
Set the country
The plugin defaults to "USA" until you specify otherwise, so the most important change is to specify the country you want to look up addresses for. You have two ways to do this:
- Set a static country using the
countryoption with an ISO 3166-1 alpha-2 or alpha-3 code (e.g., "GB", "GBR", "DE", "FR").
const autocomplete = await SmartyAddress.create({
embeddedKey: "your-smarty-embedded-key",
country: "GBR",
streetSelector: "#street",
secondarySelector: "#secondary",
localitySelector: "#city",
administrativeAreaSelector: "#state",
postalCodeSelector: "#zipcode",
});- Let the user set the country through a form field using countrySelector, which points to a field (such as a text input where they enter a country code like "GBR") whose value is read at lookup time. If both are set, countrySelector takes precedence over country.
So in the form, add <input type="text" id="country" placeholder="Country code (e.g. GBR)" />, like this:
<form>
<input type="text" id="country" placeholder="Country code (e.g. GBR)" />
<input type="text" id="street" placeholder="Start typing an address..." />
<input type="text" id="secondary" />
<input type="text" id="city" />
<input type="text" id="state" />
<input type="text" id="zipcode" />
</form>And the script should include countrySelector, like this:
const autocomplete = await SmartyAddress.create({
embeddedKey: "your-smarty-embedded-key",
countrySelector: "#country",
streetSelector: "#street",
secondarySelector: "#secondary",
localitySelector: "#city",
administrativeAreaSelector: "#state",
postalCodeSelector: "#zipcode",
});Whatever the user types into the country field is what the plugin sends as the country on each lookup, so once they enter "GBR", the autocomplete solution only pulls UK addresses. If they change it to "CAN" and keep typing an address, the very next lookup (keystroke) brings up Canadian addresses.