Populate input fields on form submit

时间:2016-04-15 11:13:55

标签: javascript jquery

I have the following HTML form:

<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>

On the submit button press I would like to set the values for latitude and longitude fields and the proceed with the action to my controller.

Here is the JavaScript function for getting lat and long.

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.');
}

What would be the most reasonalbe way to fill the values (js and jQuery are OK) and then proceed with the logic?

Any help or guidance is much appreciated.

2 个答案:

答案 0 :(得分:2)

没有一种很好的方法可以做到这一点。

由于iframe是异步的,唯一的方法是:

  1. 防止默认提交行为
  2. 触发异步功能
  3. 填充回调中的字段
  4. 使用JavaScript触发表单提交
  5. 在页面加载时简单地尝试填充字段会更容易,这样在填写表单时,数据就会存在。

答案 1 :(得分: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
}