Reputation: 2775
I'm using Google maps autocomplete script and its working fine, but how to clear input if user has not select anyone from a dropdown list?
For example: Current situation: User enter "New" and see "New york" in a list, but do not choose it (clicks anywhere outside the input), and now intup has value "New". I want: User enter "New" and see "New york" in a list, but do not choose it (clicks anywhere outside the input), and now intup has empty value, because nothing in the list is not selected.
My current code:
<input id="autocomplete2" placeholder="Enter your address" onFocus="initAutocomplete2()" type="text">
<script>
function initAutocomplete2() {
autocomplete2 = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autocomplete2')),
{types: ['(cities)']});
}
</script>
Upvotes: 1
Views: 5048
Reputation: 1070
I found a way that seems better to me, you can define an "old value" that changes only by "place_changed" callback. Then, on "blur" event you should refill the value with last picked one (or the initial value). This way the field value is consistent, it's empty or a valid picked value.
var oldaddress = $("input[name='address']").val();
$("input[name='address']").on('blur', function () {
$(this).val(oldaddress);
});
function initAutocomplete() {
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('address'),
{types: [(cities)]}
);
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
var place = autocomplete.getPlace();
// ....
oldaddress = $("input[name='address']").val();
}
Upvotes: 0
Reputation: 62536
You will need to have a variable to save the fact that a value was selected, and then when someone focus/blur the input - reset the value of the input if needed.
Here is an example:
var selected = false;
function initAutocomplete2() {
autocomplete2 = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autocomplete2')),
{types: ['(cities)']});
autocomplete2.addListener('place_changed', function() {
selected = true
});
}
$('#autocomplete2').on('focus', function() {
selected = false;
}).on('blur', function() {
if (!selected) {
$(this).val('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="autocomplete2" placeholder="Enter your address" onFocus="initAutocomplete2()" type="text">
Upvotes: 11