在建议选择上提交地理填写表单

时间:2015-02-22 14:28:41

标签: javascript geocomplete

我对JS很新,所以我有点困惑,为什么这不起作用。 基本上我使用geocomplete jQuery插件来填充带有坐标和地址的表单。然后,一旦用户选择了目的地,我想要对表格进行总结。

 <form action="search.php" method="post" id="searchForm">
        <input id="geocomplete" type="text" placeholder="Where are you going to?" size="35" />
        <input name="lat" type="hidden" value="">
        <input name="lng" type="hidden" value="">
        <input name="formatted_address" type="hidden" value="" id="address">
    </form>

这将是我调用以启动表单插件(可以工作)的脚本,以及在插件更改地址值后提交表单的脚本:

<script type="text/javascript">
window.onload= function () {
    if(window.addEventListener) {
        document.getElementById('address').addEventListener('change', doIt, false);
    } else if (window.attachEvent){
        document.getElementById('address').attachEvent("onchange", doIt);
    }

    function doIt(){
        document.getElementById("searchForm").submit();
    }
}

$("input").geocomplete({ details: "form" }); 


</script>

我不明白为什么这不会起作用,因为值会发生变化。非常感谢!

3 个答案:

答案 0 :(得分:3)

change事件仅在直接用户输入发生更改时触发,而不是在脚本更改输入值时触发。

使用该插件提供的事件,如您已链接到的页面所述。

答案 1 :(得分:1)

这是jquery的另一个解决方案。这会在单击自动填充的地址时强制提交,或者用户使用箭头键选择它并按下输入。允许地理编码库填充隐藏字段的延迟为1.5秒。这需要延迟是'onchange="this.form.submit()"对我无效的原因。

  /*
    submit form when user clicks or hits enter on auto suggest 
    must sleep for 2 seconds to allow the geocoding library to update the hidden fields
  */
  $(document).ready(function(){
    $('#geocomplete').change(function(){
      setTimeout(function() {
        $('#find').click()     
      }, 1500);
    });
  });
  $(document).ready(function(){
    $('#geocomplete').keydown(function(event){
      if (event.keyCode == 13) {
        setTimeout(function() {
          $('#find').click()     
        }, 1500);
        return false;
      }
    });
  });

答案 2 :(得分:1)

$(function(){
    $(".geocomplete")
       .geocomplete({details:"form"})
       .bind("geocode:result", function(event, result){$(".searchForm").submit();
        });
    });