0

我有一个事件监听器和一个表单。当用户按下回车键时,两者都会启动。我想要的是当用户按下回车键时,第一个事件侦听器应该执行,然后是表单提交。那么该怎么做呢?

 google.maps.event.addListener(autocomplete, 'place_changed', function() {

    // fires when enter key is pressed
     infowindow.close();
      marker.setVisible(false);
      input.className = '';
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        // Inform the user that the place was not found and return.
        input.className = 'notfound';
        return;
      }
    }

    and

    <form action="xyz.php" method="post">
    //submits when enter key is pressed
    <div id="searchWrapper" style="width:940px;margin-bottom:10px">

        <input name="txtSearch" type="text" id="txtSearch" class="search focus" placeholder="Where do you need parking?" value=<?php echo '"'.$str.'"'; ?> />

        <input class="dates search search-date" style="height:30px;background-image:url('images/sprite-master.png') ;background-position:-480px 0px; cursor:pointer;width:110px;" name="txtSearchStartDate" type="text" id="txtSearchStartDate" placeholder="today" enddate="txtSearchEndDate" />
        <input name="txtSearchEndDate" type="text" id="txtSearchEndDate" class="dates search search-date" placeholder="(optional)" />
        <input type="submit" value="  Search" id="btnSearch" class="btn btn-primary" />
         <input name="city" id="city" type="hidden" value="">
       <input name="state" id="state" type="hidden" value="">
       <input name="country" id="country" type="hidden" value="">
          <input name="lat" id="lat" type="hidden" value="">
       <input name="long" id="long" type="hidden" value="">
    </div>
    </form>
4

1 回答 1

0

停止表单 onsubmit 函数提交表单,检查是否在place_changed事件中给出了位置。如果是,请手动提交表单,否则更改输入的类名。

var form = document.getElementById("searchForm"), // I assume the form tag has the ID searchForm
    input = document.getElementById("txtSearch"),
    autocomplete = new google.maps.places.Autocomplete(input);

form.onsubmit = function(event) {
    // stop the form from submitting
    event.preventDefault();
};

google.maps.event.addListener(autocomplete, 'place_changed', function() {
    input.className = '';
    var place = autocomplete.getPlace();
    if (!place.geometry) {
        // Inform the user that the place was not found and return.
        input.className = 'notfound';
    } else {
        input.className = '';
        // this won't fire the onsubmit function
        form.submit();
    }
});
于 2013-03-08T17:01:52.790 回答