Próbowałem powyższe krótkie odpowiedzi, ale nie dla mnie, a długie odpowiedzi Nie chciałam je wypróbować, więc stworzyłem następujące kod, który działał całkiem dobrze dla mnie. See Demo
Załóżmy jest to Twoja forma:
<form action="" method="">
<input type="text" name="place" id="google-places-searchbox" placeholder="Enter place name"><br><br>
<input type="text" name="field-1" placeholder="Field 1"><br><br>
<input type="text" name="field-2" placeholder="Field 2"><br><br>
<button type="submit">Submit</button>
</form>
Wtedy następujący kod javascript rozwiąże problem:
var placesSearchbox = $("#google-places-searchbox");
placesSearchbox.on("focus blur", function() {
$(this).closest("form").toggleClass('prevent_submit');
});
placesSearchbox.closest("form").on("submit", function(e) {
if (placesSearchbox.closest("form").hasClass('prevent_submit')) {
e.preventDefault();
return false;
}
});
A oto jak pełny kod wygląda na stronie HTML (Uwaga musisz zastąpić YOUR_API_KEY
swoim kluczem Google api):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Prevent form submission when choosing a place from google places autocomplete searchbox</title>
</head>
<body>
<form action="" method="">
<input type="text" name="place" id="google-places-searchbox" placeholder="Enter place name"><br><br>
<input type="text" name="field-1" placeholder="Field 1"><br><br>
<input type="text" name="field-2" placeholder="Field 2"><br><br>
<button type="submit">Submit</button>
</form>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Google Maps -->
<!-- Note that you need to replace the next YOUR_API_KEY with your api key -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"
async defer></script>
<script>
var input = document.getElementById("google-places-searchbox");
var searchBox = new google.maps.places.SearchBox(input);
var placesSearchbox = $("#google-places-searchbox");
placesSearchbox.on("focus blur", function() {
$(this).closest("form").toggleClass('prevent_submit');
});
placesSearchbox.closest("form").on("submit", function(e) {
if (placesSearchbox.closest("form").hasClass('prevent_submit')) {
e.preventDefault();
return false;
}
});
</script>
</body>
</html>
To spowoduje anulowanie przesyłania z pola zawsze. Potrzebuję go tylko, aby anulować przesyłanie, jeśli użytkownik nacisnął intro, aby wybrać opcję autouzupełniania. –
Działa jak klejnot. Naciśnięcie i wybranie opcji autouzupełniania z listy przy użyciu klawisza Enter nie powoduje już przesyłania formularza. –
Jest to bardziej nietypowy wzór niż rozwiązanie. Taki sam jak użycie programu obsługi onClick do przesłania formularza zamiast obsługi onSubmit. Enter powinien przesłać formularz. –