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

和自甴很熟 提交于 2019-12-10 15:18:55

问题


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!


回答1:


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.




回答2:


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 


来源:https://stackoverflow.com/questions/14688150/triggering-google-places-autocomplete-places-places-changed-when-text-input-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!