2013-05-16 83 views
0

我有一些代碼,當點擊搜索框時,地理位置框中的位置(除非已經由autosuggest完成)並且應該提交表單。Jquery - 未提交表單

問題是,單擊搜索按鈕並且地理編碼成功後,表單不會被提交。誰能告訴我我要去哪裏?

這是對的jsfiddle鏈接:http://jsfiddle.net/sR4GR/35/

這是全碼:

$(function() { 

    var input = $("#loc"), 
     lat = $("#lat"), 
     lng = $("#lng"), 
     lastQuery = null, 
     autocomplete; 

    function processLocation(query) { 
     var query = $.trim(input.val()), 
      geocoder; 

     if (!query || query == lastQuery) { 
      console.log("Empty or same variable"); 
      return; 
     } 

     lastQuery = query; 

     geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({ 
      address: query 
     }, function (results, status) { 
      if (status === google.maps.GeocoderStatus.OK) { 
       lat.val(results[0].geometry.location.lat()); 
       lng.val(results[0].geometry.location.lng()); 
      } else { 
       alert("We couldn't find this location. Please try an alternative"); 
      } 
     }); 
    } 

    autocomplete = new google.maps.places.Autocomplete(input[0], { 
     types: ["geocode"], 
     componentRestrictions: { 
      country: "uk" 
     } 
    }); 

    google.maps.event.addListener(autocomplete, 'place_changed', processLocation); 

    $('#searchform').on('submit', function (event) { 
     processLocation(); 
     event.preventDefault(); 
    }); 
}); 
+0

'event.preventDefault();'可能是問題 – Ramunas

+0

我也這麼認爲,但是我需要這個來阻止沒有位置的表單被提交的表單首先進行地理編碼:s – Jimmy

+0

您是否可以不在文本字段的更改事件上運行processLocation()並在提交值有效之前禁用提交按鈕? – slinky2000

回答

1

我不知道是什麼processLocation(query)預計,query,但想法是這樣的:
1.改變函數簽名

function processLocation(query, doSubmit) { // <--- new parameter 
    var query = $.trim(input.val()), 
     geocoder; 

    if (!query || query == lastQuery) { 
     console.log("Empty or same variable"); 
     return; 
    } 

    lastQuery = query; 

    geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 
     address: query 
    }, function (results, status) { 
     if (status === google.maps.GeocoderStatus.OK) { 
      lat.val(results[0].geometry.location.lat()); 
      lng.val(results[0].geometry.location.lng()); 
      if (doSubmit){ 
       $('#searchform').submit(); //<-- new param usage 
      } 
     } else { 
      alert("We couldn't find this location. Please try an alternative"); 
     } 
    }); 
} 

2.刪除此調用

$('#searchform').on('submit', function (event) { 
    alert('Submitted') 
    event.preventDefault(); 
}); 

3.加這個電話

$('#search').click(function(){ 
    processLocation(new Date(), true); //<-- don't know what's the first param 
}); 

試圖在你的jsfiddle玩耍,但沒有成功,因爲我不斷得到Empty or same variable消息到控制檯。我認爲你知道你的邏輯更好,你會發現

0

我只想已經提交按鈕禁用,直到值是有效的?

<input type="submit" value="Search" id="search" disabled="disabled"> 

search.removeAttr('disabled') 

http://jsfiddle.net/sR4GR/38/

+0

嗨Stefan,這樣的事情可能會起作用,但從可用性的角度來看它並不是那麼好,特別是因爲它不是必需的字段。 – Jimmy