Keep User Input Visible After Selection

This example demonstrates how to retain the selected address in the input field, providing a better user experience by allowing users to see and confirm their choice.

By default, the input field is cleared after a selection is made. However, you can override this by setting the clear_input option to false. This is particularly useful in forms where users may want to review their selected address before proceeding.

powered by
powered by Google

Step-by-Step Implementation

To improve form usability, you can prevent the input field from clearing after a user selects an address. This allows them to review their choice before submission.

Here’s how to implement this feature:

  1. Configure the `clear_input` Option: When initialising the PlacesAutocomplete component, pass clear_input: false within the options object.
  2. Enhance User Confidence: With this setting, the selected address remains visible in the input field, giving users a chance to confirm their entry is correct before moving on. This simple adjustment makes the form feel more intuitive and reliable.
<script>
import { PlacesAutocomplete } from 'places-autocomplete-js';

document.addEventListener('DOMContentLoaded', () => {
  try {
    const autocomplete = new PlacesAutocomplete({
      containerId: 'autocomplete-container',
      googleMapsApiKey: 'YOUR_GOOGLE_MAPS_API_KEY', // Replace with your actual key
      onResponse: (placeDetails) => {
        console.log('Place Selected:', placeDetails);
      },
      onError: (error) => {
        console.error('Autocomplete Error:', error.message || error);
      },
       options:{
          clear_input: false, // Retain input value after selection
        }
    });
  } catch (error) {
    console.error("Failed to initialize PlacesAutocomplete:", error.message);
  }
});

</script>

...
<div id="autocomplete-container"></div>
...