私は上記の短い答えを試みたが、彼らは私のために動作しませんでした、と長い答えは、私はそれらを試してみたくなかったので、私は次のように作成しました私にとってはかなりうまくいったコードです。 See Demo
これはあなたのフォームであると仮定します
<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>
その後、次のJavaScriptコードは、問題を解決します:
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;
}
});
そしてここでは、完全なコードはHTMLページ(注どのように見えるかですYOUR_API_KEY
を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>
出典
2017-03-05 18:59:49
Amr
これはフィールドからの送信を常にキャンセルします。ユーザがオートコンプリートオプションを選択するためにイントロを押した場合、送信をキャンセルする必要があります。 –
宝石のように機能します。入力してリストからオートコンプリートオプションを選択しても、フォームを送信しなくなりました。 –
これは解決策よりも、よりアンティパターンです。 onSubmitハンドラの代わりにフォームを送信するonClickハンドラの使用法と同じです。入力はフォームを提出する必要があります。 –