Reputation: 921
I have a form that implements Google Places to autocomplete and populate other text fields.
<script type="text/javascript">
$(document).ready(function(){
$('.noEnterSubmit').keypress(function(e){
if ( e.which == 13 ) return false;
});
var updateAddress = {
autocomplete: new google.maps.places.Autocomplete($("#Subscription_address")[0], {types: ['geocode']}),
event: function(){
var self = this;
google.maps.event.addListener(self.autocomplete, 'place_changed', function() {
var place = self.autocomplete.getPlace(),
address = place.address_components,
streetAddress = '',
suburb = '',
state = '',
zip = '',
country = '';
for (var i = 0; i < address.length; i++) {
var addressType = address[i].types[0];
if (addressType == 'subpremise') {
streetAddress += address[i].long_name + '/';
}
if (addressType == 'street_number') {
streetAddress += address[i].long_name + ' ';
}
if (address[i].types[0] == 'route') {
streetAddress += address[i].long_name;
}
if (addressType == 'locality') {
suburb = address[i].long_name;
}
if (addressType == 'administrative_area_level_1') {
state = address[i].long_name;
}
if (addressType == 'postal_code') {
zip = address[i].long_name;
}
if (addressType == 'country') {
country = address[i].long_name;
}
}
// update the textboxes
setTimeout(function(){$('#Subscription_address').val(streetAddress).blur(function(e){
this.value = this.streetAddress;
});},50);
$('#Subscription_city').val(suburb);
$('#Subscription_state').val(state);
$('#Subscription_zip').val(zip);
$('#Subscription_country').val(country);
});
}
};
updateAddress.event();
});
</script>
</head>
<input class="noEnterSubmit input-large" name="Subscription[address]" id="Subscription_address" type="text">
I am blocking the form from submitting on enter keypress. It is only when the user enter keypress then focus off of the text field does the #Subscription_address reset and the Google Places API shows an "Undefined" value for #Subscription_address.
Currently tab keypress and mouse selection as a blur event work as expected to populate other fields and retain only the streetAddress in the #Subscription_address field.
Using JQuery how do I allow the user to select autocomplete result by using enter keypress then focus off the text field and retain selected value?
Upvotes: 3
Views: 2859
Reputation: 921
// update the textboxes
setTimeout(function(){$('#Subscription_address').val(streetAddress).blur(function(e){
this.value = streetAddress;
});},50);
I needed to remove this.streetAddress after blur function. this had a different context when in the DOM of the dropdown.
Upvotes: 1