SO I have a google maps autocomplete on a form of mine, and when it gets a place it takes the place and formats it so that all the correct information goes into different inputs on the form.
The issue I'm having is before the 'place_changed' event fires the autocomplete populates the input. I want to prevent that initial population and instead populate with what I want to be there.
I tried doing a change event but it doesnt seem to fire correctly. Here is my code:
html:
<input type="text" name="address1" value="1255 W Washington St" required="" class="form-control" id="id_address1" placeholder="Enter a location" autocomplete="var input = /** @type {HTMLInputElement} */(
js:
document.getElementById('id_address1'));
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addDomListener(input, 'keydown', function(e) {
if (e.keyCode == 13) {
e.preventDefault();
console.log('enter');
}
});
google.maps.event.addDomListener(input, 'focusout', function(e) {
if ($('#id_address1').val() != $('#id_address1').attr('value')){
$('#id_address1').val($('#id_address1').attr('value'));
}
});off"
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (place.address_components) {
var address = '';
for (var i = 0; i < place.address_components.length; i++){
switch (place.address_components[i].types[0]){
case 'street_number':
address = place.address_components[i].short_name;
break;
case 'route':
address += ' ' + place.address_components[i].short_name;
break;
case "locality":
$('#id_city').val(place.address_components[i].short_name);
break;
case "administrative_area_level_1":
$('#id_state').val(place.address_components[i].short_name);
break;
case "country":
$('#id_country').val(place.address_components[i].short_name);
break;
case "postal_code":
$('#id_zip_code').val(place.address_components[i].long_name);
break;
}
}
$('#id_address1').val(address);
$('#id_address1').attr('value', address);
}
right now when the setting the attr and then checking on focusout is a workaround because when i select a place using just the keyboard it tries to input the original full string back in.