Hello, i want to know, is there any way to force user can only select the address provided in dropdown list?

Currently everything working well, but user can proceed without select the address from the dropdown list, can anyone help? Thanks in advance

<input type="text" class="form-control" id="address" name="address" required>



<script>
   options = {
                            language: 'en-AU',
                            types: ['geocode'],
                            componentRestrictions: { country: "my" }
                        }
                        var autocomplete = new google.maps.places.Autocomplete($("#address")[0], options);

                        google.maps.event.addListener(autocomplete, 'place_changed', function() {
                                                    var place = autocomplete.getPlace();
                                                    console.log(place.address_components);
                        });
</script>

You can't prevent the user from just typing and hitting enter, but you can know if he picked an option or not.

From google docs about place_changed event:

This event is fired when a PlaceResult is made available for a Place the user has selected. If the user enters the name of a Place that was not suggested by the control and presses the Enter key, or if a Place detail request fails, a place_changed event will be fired that contains the user input in the name property, with no other properties defined.

So you can just check if any properties other than name are filled, if they aren't it means that the user didn't selected a option.

https://developers.google.com/maps/documentation/javascript/reference#Autocomplete

Hello, thanks for your reply. But i not really understand with that, anything to do with the code? or something else?

google.maps.event.addListener(autocomplete, 'place_changed', function() {
    var place = autocomplete.getPlace();
    if(place.address_components !== undefined && place.address_components.length > 0 ) {
        // selected option
    }
    else {
        // just typed and hit enter (no option selected)
    }
});

Work Perfectly ! Thanks many many to you !

You're welcome.
Just close the topic please. If you have futher questions you should open a new one =)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.