Passing result from Google distancematrix to each element in table

Passing result from Google distancematrix to each element in table

Hello, I currently have a task that requires me to retrieve the distance between two selected drop-down locations and run them through Google's distancematrix API which returns a "distance".  I am then supposed to pass that distance value to a field in the table, but the caveat is that the table is dynamic and needs to allow for added rows if necessary.

My current setup, I can pass the result to the t_mileage field, but the on change event passes the final value to all totals and not each.

Here is my code:

  1. $(document).ready(function (){
  2.   $('.ro input').attr('readonly','True');
  3.   $('.ro select').attr('readonly','True');
  4.   $('.personcheck').on('blur', 'select', errorcheck);
  5.   $('.personcheck').on('click', errorcheck);
  6.   $('.personcheck').on('change', errorcheck);
  7.   $('.starting_city select').on('change', mileage_calc);
  8.   $('.ending_city select').on('change',  mileage_calc);
  9.   //$('Field475-1').on('click', mileage_calc);
  10.   
  11. function mileage_calc(){
  12.     $('.miletable tbody tr').each(function(distance){
  13.     var scity      =   $(this).find('.starting_city :selected').val();
  14.     var sstate    =   $(this).find('.starting_state :selected').val();
  15.     var ecity      =   $(this).find('.ending_city :selected').val();
  16.     var estate    =   $(this).find('.ending_state :selected').val();
  17.     source = (scity + ', ' + sstate);
  18.     destination = (ecity + ', ' + estate);
  19. var request = {origin: source, destination: destination, travelMode: google.maps.TravelMode.DRIVING};
  20.     var service = new google.maps.DistanceMatrixService();
  21.     service.getDistanceMatrix({origins: [source],destinations: [destination],travelMode: google.maps.TravelMode.DRIVING,unitSystem: google.maps.UnitSystem.IMPERIAL,avoidHighways: false,avoidTolls: false}, 
  22.             function(response, status) {
  23.         if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
  24.             var distance = response.rows[0].elements[0].distance.value / 1000;
  25.                  
  26.                   alert(math.ceil(distance)); 
  27.                   //$('.t_mileage input').val(Math.ceil(distance)); //adds initial response to both lines
  28.                   //$(this).('.t_mileage input').val(Math.ceil(distance)); //breaks loop/function
  29.                   //$(this).find('.t_mileage input').val(distance); //doesn't work
  30.                   $(event.target).closest('tr').find('.t_mileage :input').val(Math.ceil(distance)); //doesn't work
  31.        
  32.     })
  33.     })
  34. }
And this is what the page looks like:


I have been working on this for quite some time now with no results. Please help as I am at my wits end...