2016-04-15 69 views
0

我有以下HTML形式:填充的表單輸入字段提交

<form action="http://.../index.php/timer/start_timer" class="start_timer" id="start_timer" method="post" accept-charset="utf-8"> 
    <input type="hidden" name="shift_id" value="290"> 
    <input type="hidden" name="latitude" id="latitude"> 
    <input type="hidden" name="longitude" id="longitude"> 
    <input type="submit" value="Start"> 
    </form> 

submit按下按鈕,我想爲latitudelongitude字段設置的值,並用行動來我的控制器進行。

這裏是獲得latlongJavaScript函數。

function startStopTimerSubmit(){ 

    navigator.geolocation.getCurrentPosition(foundLocation, noLocation); 

} 

function foundLocation(position){ 

    var lat = position.coords.latitude; 
    var long = position.coords.longitude; 
    document.getElementById('latitude').value = lat; 
    document.getElementById('longitude').value = long; 

} 

function noLocation() 
{ 
    alert('Could not find your location. Please, try again.'); 
} 

什麼是最reasonalbe的方式來填補值(jsjQuery都OK),然後用邏輯進行?

任何幫助或指導,非常感謝。

+0

在另一個函數定義功能是不好的做法。 –

+0

正確和謝謝。這已更新。然而,解決這個問題的正確方法仍然存在問題。 – WpDoe

+0

@MilindAnantwar - 不,它不是。這是JS用於範圍界定的核心功能。 – Quentin

回答

2

有沒有一個很好的方式來做到這一點。

由於getCurrentPosition是異步的,只有這樣,才能做到這將是:

  1. 阻止默認提交行爲
  2. 觸發異步功能
  3. 填充回調
  4. 觸發領域使用JavaScript提交表格

簡單地嘗試t o在頁面加載時填充字段,以便填充表單時數據將在那裏。

0

您可以在繼續使用嵌套函數之前檢查該字段是否已填充。這將喜歡的東西有點像......

function submit() { 
 
    var latField = $('.lat-field'); 
 
    
 
    getLatLng(function(lat, lng) { 
 
     latField.val(lat); 
 
     latField.hasValue = true; 
 
     submit(); //call submit again now value has been populated 
 
    }); 
 
    
 
    //dont proceed if value has not been set 
 
    if(!latField.hasValue) return; 
 
    
 
    //Your standard functionality here 
 
}