【问题标题】:Google Maps Autocomplete - Find autocomplete HTML to use as jQuery selectorGoogle Maps Autocomplete - 查找自动完成 HTML 以用作 jQuery 选择器
【发布时间】:2017-10-17 16:39:19
【问题描述】:

TL;DR - 有谁知道 Google 地图自动完成下拉菜单的 ID 是什么?


我在我的网站上以表格形式使用 Google 地图。我想使用 jQuery 提醒用户从 Google 为您提供的自动完成选项中列出的选项中选择一个选项。如果用户点击输入,但没有选择其中一个选项,我想显示通知。

但是,我似乎无法在弹出的选项列表中找到 ID。 (或 div 或其他 HTML。)这些选项的元素中不会出现任何内容。

例如:

这是我的代码:

HTML

<label for="title" class="form-title">Location</label>
<div class="form-row">
  <div class="form-group">
    <label>Street Address</label>
    <input type="text" id="formatted_address" name="formatted_address">
  </div>
  <div id="my_map"></div>
</div>

Javascript

<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places&language=en"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/geocomplete/1.7.0/jquery.geocomplete.min.js"></script>

代码

      $("input#formatted_address").geocomplete({
          details: "form",
          map: "#my_map" });

谢谢!

【问题讨论】:

  • 你包括jQuery UI吗? jQuery 没有自动完成的“小部件”。 jQuery UI 的 autocomplete 有一个 select 回调。您可以使用其中的event 参数来查找列表项,最后是ID。不是 100% 肯定,但这样的事情应该可以工作:var selected_item_id = $(event.target).attr('id');
  • @AlmostPitt 试试我的解决方案
  • 您使用的是 Google Maps Javascript API v3 吗?嵌入式谷歌地图? (地图的代码是什么样的?)
  • @AaronEveleth,不,谷歌地图本身有自动完成小部件。但你有一个好主意。我也尝试过类似的东西。我会在上面贴出来。
  • @geocodezip,是的,我相信我正在使用 Google Maps Javascript API v3。它是一个嵌入式地图。我会把上面的代码贴出来。

标签: jquery html google-maps autocomplete


【解决方案1】:

将侦听器添加到您的自动完成输入元素。这将触发 每当用户从自动完成列表的下拉列表中选择选项时

//Declare variable to identify option from autocomplete selected or not
var selected_from_autocmp_flag = false;

address_element = new google.maps.places.Autocomplete($("#input_element_id"));
address_element.addListener('place_changed', place_changed);

function place_changed(){
  // set flag to true 
  selected_from_autocmp_flag = true;
}

$("#input_element_id").click(function(){
  // set flag to false whenever user clicks it
  selected_from_autocmp_flag = false;  
})

假设您在 HTML 页面中有输入元素,如下所示

<input type=text id="input_element_id" placeholder="search here"/>

【讨论】:

  • 感谢您的回复@Krishnar。不幸的是,我得到了错误: InvalidValueError: not an instance of HTMLInputElement and Uncaught TypeError: a.getAttribute is not a function.
  • @AlmostPitt Brother 你是按原样粘贴的吗?你应该用你的元素 id 代替 input_element_id。检查我更新的代码。
  • 好问题。不,我更改它以添加正确的 ID。实际上,现在我可以看到当我单击该输入框时我得到“formatted_address”,但是当我选择其中一个选项时,我会看到“未定义”。不过,我仍然有错误。
  • @AlmostPitt 这应该可以。如果有任何疑虑/怀疑如何使用,请告诉我
  • 是的,你介意帮我用吗?我不断收到这些错误:“Uncaught TypeError: a.getAttribute is not a function”和“InvalidValueError: not an instance of HTMLInputElement”
猜你喜欢
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 2011-12-26
  • 2014-12-26
  • 1970-01-01
  • 2011-04-20
  • 2017-09-06
相关资源
最近更新 更多