Google Rehber Otomatik Tamamlama kullanıyorum ve yalnızca form alanındaki enter tuşuna basıldığında ve öneriler bulunduğunda sonuçlar listesindeki en üstteki öğeyi seçmesini istiyorum. Bunun daha önce sorulduğunu biliyorum:
Google Haritalar API V3 otomatik tamamlama konumunu eşler - girildiğinde ilk seçeneği seçin
Ancak bu sorulardaki cevaplar aslında işe yaramadı veya belirli bir ek işlevsellik ele alıyor.
Ayrıca aşağıdaki gibi çalışması gereken bir şey gibi görünüyor (ama işe yaramaz):
$("input#autocomplete").keydown(function(e) {
if (e.which == 13) {
//if there are suggestions...
if ($(".pac-container .pac-item").length) {
//click on the first item in the list or simulate a down arrow key event
//it does get this far, but I can't find a way to actually select the item
$(".pac-container .pac-item:first").click();
} else {
//there are no suggestions
}
}
});
Herhangi bir öneriniz çok takdir edilecektir!
En iyi cevabın bu (Not: ne yazık ki, öyle olmadığını) bulmadan önce, bu sorunun birçok cevabını ve bağlantılı soruların cevaplarını defalarca okudum. kabul edilen cevap!).
2 veya 3 satırı değiştirdim kodunuza kopyalayıp yapıştırabileceğiniz kullanıma hazır bir işleve dönüştürmek için ve gerekirse birçok input
öğesine uygulayabilirsiniz. İşte burada:
var selectFirstOnEnter = function(input){
// store the original event binding function
var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;
// Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected, and then trigger the original listener.
function addEventListenerWrapper(type, listener) {
if (type == "keydown") {
var orig_listener = listener;
listener = function (event) {
var suggestion_selected = $(".pac-item-selected").length > 0;
if (event.which == 13 && !suggestion_selected) {
var simulated_downarrow = $.Event("keydown", { keyCode:40, which:40 });
orig_listener.apply(input, [simulated_downarrow]);
}
orig_listener.apply(input, [event]);
};
}
// add the modified listener
_addEventListener.apply(input, [type, listener]);
}
if (input.addEventListener) {
input.addEventListener = addEventListenerWrapper;
} else if (input.attachEvent) {
input.attachEvent = addEventListenerWrapper;
}
}
Kullanımı:
selectFirstOnEnter(input1);
selectFirstOnEnter(input2);
...
Çok daha iyi ve temiz bir çözüm var gibi gözüküyor: google.maps.places.SearchBox
..__ yerine google.maps.places.Autocomplete
kullanmak, bir kodun neredeyse aynı olması, ilk önce birden fazla yerden alınması. Enter'a bastığınızda doğru liste döndürülür - kutudan çıkar ve bilgisayar korsanlarına gerek kalmaz.
Örnek HTML sayfasına bakın:
İlgili kod pasajı:
var searchBox = new google.maps.places.SearchBox(document.getElementById('searchinput'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
var place = searchBox.getPlaces()[0];
if (!place.geometry) return;
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(16);
}
});
Örneğin kaynak kodunun tamamı şudur: https://Gist.github.com/klokan/8408394
Bu aynı işlevselliği elde etmek için sitemde jQuery simule eklentisini kullandım ( https://github.com/jquery/jquery-simulate ) ve etkinliği ekleyin:
$("input#autocomplete").focusin(function () {
$(document).keypress(function (e) {
if (e.which == 13) {
$("input#autocomplete").trigger('focus');
$("input#autocomplete").simulate('keydown', { keyCode: $.ui.keyCode.DOWN } ).simulate('keydown', { keyCode: $.ui.keyCode.ENTER });
}
});
});
Eklenti, AŞAĞI tuşuna ve ardından ENTER tuşuna basma eylemini taklit eder, ENTER kendisi çalışmaz ve ilk seçeneği seçmenin başka bir yolunu bulamadım.
Bu yardımcı olur umarım
Yanlış gezinmeyi tetiklemek yerine, kullanıcının listede klavyeyle gezinmeye başlayıp başlamadığını dinleyen Çalışma Çözümü
https://codepen.io/callam/pen/RgzxZB
İşte önemli bitler
// search input
const searchInput = document.getElementById('js-search-input');
// Google Maps autocomplete
const autocomplete = new google.maps.places.Autocomplete(searchInput);
// Has user pressed the down key to navigate autocomplete options?
let hasDownBeenPressed = false;
// Listener outside to stop nested loop returning odd results
searchInput.addEventListener('keydown', (e) => {
if (e.keyCode === 40) {
hasDownBeenPressed = true;
}
});
// GoogleMaps API custom eventlistener method
google.maps.event.addDomListener(searchInput, 'keydown', (e) => {
// Maps API e.stopPropagation();
e.cancelBubble = true;
// If enter key, or tab key
if (e.keyCode === 13 || e.keyCode === 9) {
// If user isn't navigating using arrows and this hasn't ran yet
if (!hasDownBeenPressed && !e.hasRanOnce) {
google.maps.event.trigger(e.target, 'keydown', {
keyCode: 40,
hasRanOnce: true,
});
}
}
});
// Clear the input on focus, reset hasDownBeenPressed
searchInput.addEventListener('focus', () => {
hasDownBeenPressed = false;
searchInput.value = '';
});
// place_changed GoogleMaps listener when we do submit
google.maps.event.addListener(autocomplete, 'place_changed', function() {
// Get the place info from the autocomplete Api
const place = autocomplete.getPlace();
//If we can find the place lets go to it
if (typeof place.address_components !== 'undefined') {
// reset hasDownBeenPressed in case they don't unfocus
hasDownBeenPressed = false;
}
});
Yaptığım şey bu ve işe yarıyor:
HTML:
<input name="location" id="autocomplete" autocomplete="off" type="text" class="textbx" placeholder="Enter Destination" required>
googleautocompletecustomized.js:
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
if($('#autocomplete').length){
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),
{
types: ['(regions)'],
componentRestrictions: {country: "in"}
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
$('#autocomplete').closest('form').data('changed', true);
fillInAddress();
});
}
//select first result
$('#autocomplete').keydown(function (e) {
if (e.keyCode == 13 || e.keyCode == 9) {
$(e.target).blur();
if($(".pac-container .pac-item:first span:eq(3)").text() == "")
var firstResult = $(".pac-container .pac-item:first .pac-item-query").text();
else
var firstResult = $(".pac-container .pac-item:first .pac-item-query").text() + ", " + $(".pac-container .pac-item:first span:eq(3)").text();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"address":firstResult }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
placeName = results[0];
e.target.value = firstResult;
fillInAddress(placeName);
$('#datetimepicker1 .input-group-addon').click();
}
});
}
});
}
// [START region_fillform]
function fillInAddress(place) {
// Get the place details from the autocomplete object.
if(!place)
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
Eğer Angular 2,4, 5 & 6 kullanıyorsanız, lütfen cevabı aşağıdaki linkte bulabilirsiniz.
Bana çözmenin en kolay yolu bu:
autocomplete.addListener('place_changed', function() {
if(event.keyCode == 13 || event.keyCode == 9) { // detect the enter key
var firstValue = $(".pac-container .pac-item:first").text(); // assign to this variable the first string from the autocomplete dropdown
}
$('#search-address').val(firstValue); // add this string to input
console.log(firstValue); // display the string on your browser console to check what it is
//(...) add the rest of your code here
});
}