简体   繁体   中英

Populate input fields on form submit

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.

There isn't a nice way to do this.

Since getCurrentPosition is asynchronous, the only way to do it would be to:

  1. Prevent the default submit behaviour
  2. Trigger the async function
  3. Populate the fields in the callback
  4. Trigger the form submission with JavaScript

It would be easier to simply try to populate the fields when the page loaded so that by the time the form was filled in, the data would be there.

You could check if the field has been populated before continuing with a nested function. This would like something kind of like...

 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 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM