TheMethod
TheMethod

Reputation: 3001

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!

Upvotes: 4

Views: 11072

Answers (2)

Jignesh Darji
Jignesh Darji

Reputation: 99

you can also try using autocomplete enter key event and trigger using javascript.

Please try following code.

//For Set Location pin point
var searchtext = "New York, NY";
var input = document.getElementById('pac-input');
$('#pac-input').val(searchtext);                        
setTimeout(function () {
google.maps.event.trigger(input, 'focus');
google.maps.event.trigger(input, 'keydown', { keyCode: 13 });                            
}, 10);
//End 

Upvotes: 0

Chris Green
Chris Green

Reputation: 4427

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.

Upvotes: 5

Related Questions