Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associate Google Places Autocomplete pac-container with input field

Is there any way to associate the pac-container div for an autocomplete with the input element that it's attached to? Ideally, I'd like to be able to set the ID of each pac-container to something like "pac-", so that I can delete them if the input goes away, and to make it easier to test the autocompletes with Selenium.

This question's answer has one solution, but it's not remotely sustainable, as Google has a tendency to change various minified property names (For example, what was once Mc is now Rc)

I've also tried modifying the last pac-container div on the page whenever a new autocomplete is added, like so:

function attachAutocomplete(id) {
    var input = document.getElementById(id);
    var autocomplete = new google.maps.places.Autocomplete(input);
    $(".pac-container:last").attr("id", "pac-" + id);
}

This works fine with new autocompletes beyond the ones on the page when it's loaded, but for some reason there's a delay between the first couple of autocompletes being assigned and their pac-containers showing up. (Here's a fiddle that should illustrate this approach and how it fails)

Is there some method I'm missing?

like image 846
StephenTG Avatar asked Nov 10 '22 09:11

StephenTG


1 Answers

I solved the issue not by associating every .pac-container to its input type form field, but, resetting all .pac-container items, every time an autocomplete input type is focused.

So basically:

1) let's assume we have 3 address input to which google.maps.places.Autocomplete is set up

2) using jquery, let's bind focus event to these 3 inputs

$('#address_1, #address_2, #address_2'.focus(function (e) 
{
    $('.pac-container').each( function() {
        $(this).html( '' );
    });
});

3) bind focusout event to these 3 inputs, and select the corresponding selected address

like image 164
Samuel Vicent Avatar answered Nov 14 '22 22:11

Samuel Vicent