Home > front end >  How do I change this variable using radio buttons?
How do I change this variable using radio buttons?

Time:05-27

Hello I've been tearing my hair out over this all last night and this morning, I have a radio button set with 3 options and I have a variable called "Minimum_fare". I'm trying to write javascript that will set the variable "minimum_fare" to a different number depending on which radio button is selected.

var countrycode="GB"
//Rate per km (number)
var rateperkm=1;
//Minimum fare (number)
var minimum_fare=110;
//Currrency Symbol
var currencysymbol="£";
//Avoid motorways / highways? true/false
var avoidHighways=false;
//Avoid toll roads? true/false
var avoidTolls=true;
//Show summary? true/false
var showsummary=false;
//Show Route Map
var showroutemap=true;
//rate per min
var rate_per_minute=0.916;
//API Key for map
var apikey="AIzaSyB_MrpX85obMpsk_eEdfE-iPIt06qbHyt0";
//----------End Settings--------------------------------    
function initialize() 
{
    var options = {componentRestrictions: {country: countrycode}};
    var input = /** @type {HTMLInputElement} */(document.getElementById('inputfrom'));
    var searchBoxfrom = new google.maps.places.Autocomplete(input,options);
    var input = /** @type {HTMLInputElement} */(document.getElementById('inputto'));
    var searchBoxto = new google.maps.places.Autocomplete(input,options);
}

function ftn_estimate()
{
    if (document.getElementById('inputfrom').value!="" && document.getElementById('inputto').value!="")
    {
        var origin = document.getElementById('inputfrom').value;
        var destination = document.getElementById('inputto').value;
        
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
          {
            origins: [origin],
            destinations: [destination],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: avoidHighways,
            avoidTolls: avoidTolls,
          }, callback); 
    }
}

function change_MinimumFare(sender){
    minimum_fare==parseFloat(sender.value);
    console.log('minimum_fare is : ',minimum_fare);
    }


function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: '   status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;

    for (var i = 0; i < origins.length; i  ) {
      var results = response.rows[i].elements;
      
      for (var j = 0; j < results.length; j  ) {

        

        if(showsummary)
        {
            document.getElementById('summary').innerHTML=origins[i]   ' to '   destinations[j] 
               ': '   results[j].distance.text   ' in '  results[j].duration.text
        }
        document.getElementById('distance').value=(results[j].distance.value/1000).toFixed(1);
        document.getElementById('time').value=(results[j].duration.value/60).toFixed(1);
        
        
        
        
        var calc_fare=(results[j].distance.value/1000)*rateperkm;
        
        
        
        if (calc_fare<16)
        {
            calc_fare=minimum_fare;
        }   
        else calc_fare=calc_fare minimum_fare;
        



        document.getElementById('fare').value=currencysymbol calc_fare.toFixed(2);
      }
    }
    
    if (showroutemap)
    {
        var origin = document.getElementById('inputfrom').value;
        var destination = document.getElementById('inputto').value;
        getpath(origin,destination);
    }
  }
}
google.maps.event.addDomListener(window, 'load', initialize);


function getpath(a,b) {
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer({
    preserveViewport: true
  });
  
  directionsService.route({
    origin: a,
    destination:b,
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      // directionsDisplay.setDirections(response);
    var polyline = new google.maps.Polyline({
        path: [],
        strokeColor: '#0000FF',
        strokeWeight: 3
      });
      
    var legs = response.routes[0].legs;
  
     for (i = 0; i < legs.length; i  ) {
        var steps = legs[i].steps;
        for (j = 0; j < steps.length; j  ) {
        var nextSegment = steps[j].path;
        for (k = 0; k < nextSegment.length; k  ) {
            polyline.getPath().push(nextSegment[k]);
          }
        }
      }

    do{
        var newpath = [];
            for (k = 0; k < polyline.getPath().length; k  = 2) {
                newpath.push(polyline.getPath().getAt(k));
            }
            polyline.setPath(newpath);
    }
    while (polyline.getPath().length>1000)

    var path = polyline.getPath();
    var encodeString = google.maps.geometry.encoding.encodePath(path);

       
       document.getElementById('mapspan').innerHTML='<center><img src="https://maps.googleapis.com/maps/api/staticmap?size=400x400&path=weight:3|color:red|enc:' encodeString '&key=' apikey '"/></center>';
      
    } else {
      window.alert('Directions request failed due to '   status);
    }
  });
}
<div id="mileage2" >
              
              <form id="myform">
                <div >
                <div >
              <label for="inputfrom" >Input start Postcode</label>
              <input id="inputfrom" type="text" placeholder="From Postcode">

              <br />to<br />

              <label for="inputto" >Input destination postcode</label>
              <input id="inputto" type="text" placeholder="To Postcode">
              <br />

              <input type="button" onclick="ftn_estimate();" value="Get route" />
              
              <br /><br />
              <table>
                <tr>
                  <td>Time (mins)</td>
                  <td>
                    <input id="time" readonly type="text" placeholder="--" style="width:100px"></td>
                </tr>
                <tr>
                  <td>Distance (km)</td>
                  <td>
                    <input id="distance" readonly type="text" placeholder="--" style="width:100px"></td>
                </tr>
                <tr>
                  <td>Your Quote: </td>
                  <td>
                    <input id="fare" readonly type="text" placeholder="--" style="width:100px"></td>
                </tr>
              </table>
            </div>
              <div >
                <fieldset id="menfield">
                  <div>
                    <input type="radio" id="1man" name="men" value="110"
                           checked onclick="change_MinimumFare(this)">
                    <label for="1man">1 Man</label>
                  </div>
              
                  <div>
                    <input type="radio" id="2man" name="men" value="160" onclick="change_MinimumFare(this)">
                    <label for="2man">2 Man</label>
                  </div>
              
                  <div>
                    <input type="radio" id="2man" name="men" value="200" onclick="change_MinimumFare(this)">
                    <label for="3man">3 Man</label>
                  </div>
              </fieldset>
              <script type="text/javascript">
                function change_MinimumFare(sender){
  minimum_fare=parseFloat(sender.value);
  console.log('minimum_fare is : ',minimum_fare);
  }
  </script>

              </div>
            </div>
          
            </form>
              <span id="summary"></span>
              <span id="mapspan"></span>
            </div>
            
            <script
src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry&key=AIzaSyB_MrpX85obMpsk_eEdfE-iPIt06qbHyt0" 
>
</script>

I've looked at dozens of answers on stackexchange and tried implementing everything I can think of but I'm still stuck. How can I get the radio button to set the minimum fare variable?

Snippet updated

CodePudding user response:

Does this answer your question? (reference)

var countrycode="GB"
//Rate per km (number)
var rateperkm=1;
//Minimum fare (number)
var minimum_fare=110;
//Currrency Symbol
var currencysymbol="£";
//Avoid motorways / highways? true/false
var avoidHighways=false;
//Avoid toll roads? true/false
var avoidTolls=true;
//Show summary? true/false
var showsummary=false;
//Show Route Map
var showroutemap=true;
//rate per min
var rate_per_minute=0.916;
//API Key for map
var apikey="AIzaSyB_MrpX85obMpsk_eEdfE-iPIt06qbHyt0";
//----------End Settings--------------------------------    
function initialize() 
{
    var options = {componentRestrictions: {country: countrycode}};
    var input = /** @type {HTMLInputElement} */(document.getElementById('inputfrom'));
    var searchBoxfrom = new google.maps.places.Autocomplete(input,options);
    var input = /** @type {HTMLInputElement} */(document.getElementById('inputto'));
    var searchBoxto = new google.maps.places.Autocomplete(input,options);
}

function ftn_estimate()
{
    if (document.getElementById('inputfrom').value!="" && document.getElementById('inputto').value!="")
    {
        var origin = document.getElementById('inputfrom').value;
        var destination = document.getElementById('inputto').value;
        
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
          {
            origins: [origin],
            destinations: [destination],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: avoidHighways,
            avoidTolls: avoidTolls,
          }, callback); 
    }
}




function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: '   status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;

    for (var i = 0; i < origins.length; i  ) {
      var results = response.rows[i].elements;
      
      for (var j = 0; j < results.length; j  ) {

        

        if(showsummary)
        {
            document.getElementById('summary').innerHTML=origins[i]   ' to '   destinations[j] 
               ': '   results[j].distance.text   ' in '  results[j].duration.text
        }
        document.getElementById('distance').value=(results[j].distance.value/1000).toFixed(1);
        document.getElementById('time').value=(results[j].duration.value/60).toFixed(1);
        
        
        
        
        var calc_fare=(results[j].distance.value/1000)*rateperkm;
        
        
        
        if (calc_fare<16)
        {
            calc_fare=minimum_fare;
        }   
        else calc_fare=calc_fare minimum_fare;
        



        document.getElementById('fare').value=currencysymbol calc_fare.toFixed(2);
      }
    }
    
    if (showroutemap)
    {
        var origin = document.getElementById('inputfrom').value;
        var destination = document.getElementById('inputto').value;
        getpath(origin,destination);
    }
  }
}
google.maps.event.addDomListener(window, 'load', initialize);


function getpath(a,b) {
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer({
    preserveViewport: true
  });
  
  directionsService.route({
    origin: a,
    destination:b,
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      // directionsDisplay.setDirections(response);
    var polyline = new google.maps.Polyline({
        path: [],
        strokeColor: '#0000FF',
        strokeWeight: 3
      });
      
    var legs = response.routes[0].legs;
  
     for (i = 0; i < legs.length; i  ) {
        var steps = legs[i].steps;
        for (j = 0; j < steps.length; j  ) {
        var nextSegment = steps[j].path;
        for (k = 0; k < nextSegment.length; k  ) {
            polyline.getPath().push(nextSegment[k]);
          }
        }
      }

    do{
        var newpath = [];
            for (k = 0; k < polyline.getPath().length; k  = 2) {
                newpath.push(polyline.getPath().getAt(k));
            }
            polyline.setPath(newpath);
    }
    while (polyline.getPath().length>1000)

    var path = polyline.getPath();
    var encodeString = google.maps.geometry.encoding.encodePath(path);

       
       document.getElementById('mapspan').innerHTML='<center><img src="https://maps.googleapis.com/maps/api/staticmap?size=400x400&path=weight:3|color:red|enc:' encodeString '&key=' apikey '"/></center>';
      
    } else {
      window.alert('Directions request failed due to '   status);
    }
  });
}
function change_MinimumFare(sender){
minimum_fare=parseFloat(sender.value);
console.log('minimum_fare is : ',minimum_fare);
}
<fieldset id="menfield">
                  <div>
                    <input type="radio" id="1man" name="men" value="110"
                           checked onclick="change_MinimumFare(this)">
                    <label for="1man">1 Man</label>
                  </div>
              
                  <div>
                    <input type="radio" id="2man" name="men" value="160" onclick="change_MinimumFare(this)">
                    <label for="2man">2 Man</label>
                  </div>
              
                  <div>
                    <input type="radio" id="2man" name="men" value="200" onclick="change_MinimumFare(this)">
                    <label for="3man">3 Man</label>
                  </div>
              </fieldset>
              
              <script type="text/javascript">
              function change_MinimumFare(sender){
minimum_fare=parseFloat(sender.value);
console.log('minimum_fare is : ',minimum_fare);
}
</script>
<script
src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry&key=AIzaSyB_MrpX85obMpsk_eEdfE-iPIt06qbHyt0" 
>

I have added function change_MinimumFare to both snippets since it requires full code to run

Edited to Add: added parseFloat function since calc_fare is a float variable

  • Related