Reputation: 17604
I have Google Maps Autocomplete working on severalinput
tags like this:
<input class="controls pac-input" id="pac-input" type="text" onfocus="geolocate()" placeholder="Type custom address" />
To enable Google Maps auto-complete, I have the following code:
//https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
$(document).ready(function () {
autocomplete = new google.maps.places.Autocomplete((document.getElementById('pac-input')), { types: ['geocode'] });
google.maps.event.addListener(autocomplete, 'place_changed', function () {
MyFunc();
});
});
And then, in the MyFunc()
function I do what I need:
function MyFunc() {
var fullAddress = autocomplete.getPlace().formatted_address;
var input = $(this);
//stuff that uses input
}
This code however, has two problems:
$(this)
but it aint working. How can jQuery help me ?Thanks in advance!
Upvotes: 2
Views: 2721
Reputation: 22489
You don't need jQuery for this. Here is a working example using only javascript:
HTML:
<input class="autocomplete" id="ac1" placeholder="Enter your address" type="text"></input>
<input class="autocomplete" id="ac2" placeholder="Enter your address" type="text"></input>
<input class="autocomplete" id="ac3" placeholder="Enter your address" type="text"></input>
JavaScript:
var acInputs = document.getElementsByClassName("autocomplete");
for (var i = 0; i < acInputs.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(acInputs[i]);
autocomplete.inputId = acInputs[i].id;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
console.log('You used input with id ' + this.inputId);
});
}
If you want to do it with jQuery then you can try this way:
$('.autocomplete').each(function() {
var autocomplete = new google.maps.places.Autocomplete($(this)[0]);
autocomplete.inputId = $(this).attr('id');
google.maps.event.addListener(autocomplete, 'place_changed', function () {
console.log('You used input with id ' + this.inputId);
});
});
Hope this helps.
Upvotes: 10
Reputation: 1683
In order to find out which input element is being called, you could pass the event to MyFunc()
. Using $(this)
isn't going to check outside of that function to see what called it.
Update the addListener
to the following.
google.maps.event.addListener(autocomplete, 'place_changed', function (e) {
MyFunc(e);
});`
And update MyFunc()
to
function MyFunc(e) {
var fullAddress = autocomplete.getPlace().formatted_address;
var input = e;
//stuff that uses input
}
You can then use input
as the variable that holds the information about the element being updated. If you do console.log(input);
below the var input = e;
you will see a list of items you can use to get the data.
You may be most interested in setting var input = e;
to var input = e.target;
instead. This will allow you to get the information about the input easily.
Example: input.value
would return the value of the input in question.
Upvotes: -1