TheMethod TheMethod - 4 years ago 135
jQuery Question

Triggering Google Places Autocomplete Places places changed when text input same value of one of the selections

I'm using the Google Places Autcomplete API and jQuery. It's basic functionality is working fine. What I would like to do is if someone types something into the autocomplete that is exactly the same as one of the selections I would like that item to be selected and the

place_changed
event to fire. This is because I have some logic in the places changed listener that I need to trigger. The idea is that if someone types in the exact same text as one of autocomplete options then it should act as if someone clicked on the option.

This is what I've tried, where userLocation is the input:

$("#userLocation").keyup(function(e){
//if the text is at least 4 chars long
if($("#userLocation").val().length > 4)
{
//iterate through each of the autocomplete options
$(".pac-item").each(function(){
if($(this).text() == $("#userLocation").val() )
{
//does not do what I need it to
$(this).trigger("place_changed");
}
});
}
});


I've also tried replacing the
trigger("place_changed")
with
.trigger("click")
but to no avail.

Has anyone does this before? Could anyone suggest another way to try and make this work? Any advice would be very much appreciated, thanks!

Answer Source

As mentioned in the answer here:

You must call the google.maps.event.trigger function resulting in a call like below.

$("#userLocation").keyup(function(e){
    //if the text is at least 4 chars long
    if($("#userLocation").val().length > 4)
    {
        //iterate through each of the autocomplete options
        $(".pac-item").each(function(){
            if($(this).text() == $("#userLocation").val() )
            {
                google.maps.event.trigger(autocomplete, 'place_changed');
            }
        });
    }
});

The documentation shows you can also pass arguments to the trigger function that will be passed to the event listener for 'place_changed' event.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download