1

I am trying to use inputs from a HTML form into a Javascript code. The inputs are 3 zip codes and the result is computation of distance between them and it is followed by a simple arithmetic. First I created a html form

    <form>
*Enter 5 digit US ZipCodes<br><br>
Port ZipCode:<br>
<input type="text" id="PortZip" value="31402">
<br><br>
Importer ZipCode:<br>
<input type="text" id="ImporterZip" value="30308">
<br><br>
Exporter ZipCode:<br>
<input type="text" id="ExporterZip" value="30901">
<br><br>

<input type="button" value="Calculate" onclick="initialize()" />
</form> 

Then I passed the 3 zip-codes into JS

var zipCodesToLookup1 = new Array('document.getElementById("PortZip").value', 'document.getElementById("ImporterZip").value', 'document.getElementById("ExporterZip").value', 'document.getElementById("PortZip").value');

Complete code is below-

    <html>
<head>
</head>
<body>
<form>
*Enter 5 digit US ZipCodes<br><br>
Port ZipCode:<br>
<input type="text" name="PortZip" value="31402">
<br><br>
Importer ZipCode:<br>
<input type="text" name="ImporterZip" value="30308">
<br><br>
Exporter ZipCode:<br>
<input type="text" name="ExporterZip" value="30901">
<br><br>

<input type="button" value="Calculate" onclick="initialize()" />
</form> 

<div id="zip_code_output"></div>
<div id="map_canvas" style="width:650px; height:600px;"></div>




<script type="text/javascript">
function initialize() {

     //INITIALIZE GLOBAL VARIABLES
     var zipCodesToLookup1 = new Array('document.getElementById("PortZip").value', 'document.getElementById("ImporterZip").value', 'document.getElementById("ExporterZip").value', 'document.getElementById("PortZip").value');
     var output           = '<tr><th scope="col">From</th><th scope="col">To</th><th scope="col">Miles</th></tr>';
     var difference = "0";
     var totalDist = 0;
    // document.write(difference);
     //EXECUTE THE DISTANCE MATRIX QUERY
     var service = new google.maps.DistanceMatrixService();
     service.getDistanceMatrix({
          origins:      zipCodesToLookup1,
          destinations: zipCodesToLookup1,
          travelMode:   google.maps.TravelMode.DRIVING,
          unitSystem:   google.maps.UnitSystem.IMPERIAL
     }, function(response, status) {
          if(status == google.maps.DistanceMatrixStatus.OK) {
               var origins = response.originAddresses;
               var destinations = response.destinationAddresses;
               for(var i=0; i < origins.length-1; i++) {
                     var results = response.rows[i].elements;
                     output += '<tr><td>' + origins[i] + '</td><td>' + destinations[i+1] + '</td><td>' + results[i+1].distance.text + '</td></tr>';
                     if (i != 0){
                     totalDist += results[i+1].distance.value;
                     }
                     else {
                     totalDist -= results[i+1].distance.value;
                     }

               }
              output += '<tr><td></td><td>OUT OF ROUTE DISTANCE -</td><td>'+(totalDist/1000*0.621371).toFixed(0)+ ' mi</td></tr>';


               document.getElementById('zip_code_output').innerHTML = '<table cellpadding="5">' + output + '</table>';
          }
     });
}

//FUNCTION TO LOAD THE GOOGLE MAPS API
function loadScript() {
     var script  = document.createElement("script");
     script.type = "text/javascript";
     script.src  = "http://maps.googleapis.com/maps/api/js?key=AIzaSyCDZpAoR25KSkPTRIvI3MZoAg1NL6f0JV0&sensor=false&callback=initialize";
     document.body.appendChild(script);
}

window.onload = loadScript;

</script>
?>

</body>
</html>

The code is not working. I suspect my html form code is not right. Corrections are welcomed.

4
  • The code is not working. I suspect my html form code is not right. Commented Jul 3, 2015 at 0:11
  • How are you passing the form data to javascript? There is no submit action for the form. Commented Jul 3, 2015 at 0:14
  • I tried to code by looking at a similar example link Commented Jul 3, 2015 at 0:32
  • Let us continue this discussion in chat. Commented Jul 3, 2015 at 0:32

1 Answer 1

1

dude, you are using document.getElementbyId in javascript. But where is your id in the form? you have given it as name. Also your array initialization is wrong. You are passing the paramaters as string. Modify your code as follows:

The form:

<form>
    *Enter 5 digit US ZipCodes<br><br>
    Port ZipCode:<br>
    <input type="text" id="PortZip" value="31402">
    <br><br>
    Importer ZipCode:<br>
    <input type="text" id="ImporterZip" value="30308">
    <br><br>
    Exporter ZipCode:<br>
    <input type="text" id="ExporterZip" value="30901">
    <br><br>

    <input type="button" value="Calculate" onclick="initialize()" />
</form> 

The javascript:

<script>
function initialize() {

            //INITIALIZE GLOBAL VARIABLES
            var zipCodesToLookup1 = new Array(document.getElementById("PortZip").value, document.getElementById("ImporterZip").value, document.getElementById("ExporterZip").value, document.getElementById("PortZip").value);
            var output           = '<tr><th scope="col">From</th><th scope="col">To</th><th scope="col">Miles</th></tr>';
            var difference = "0";
            var totalDist = 0;
            console.log(zipCodesToLookup1);
            // document.write(difference);
            //EXECUTE THE DISTANCE MATRIX QUERY
            var service = new google.maps.DistanceMatrixService();
            service.getDistanceMatrix({
                origins:      zipCodesToLookup1,
                destinations: zipCodesToLookup1,
                travelMode:   google.maps.TravelMode.DRIVING,
                unitSystem:   google.maps.UnitSystem.IMPERIAL
                }, function(response, status) {
                if(status == google.maps.DistanceMatrixStatus.OK) {
                    var origins = response.originAddresses;
                    var destinations = response.destinationAddresses;
                    for(var i=0; i < origins.length-1; i++) {
                        var results = response.rows[i].elements;
                        output += '<tr><td>' + origins[i] + '</td><td>' + destinations[i+1] + '</td><td>' + results[i+1].distance.text + '</td></tr>';
                        if (i != 0){
                            totalDist += results[i+1].distance.value;
                        }
                        else {
                            totalDist -= results[i+1].distance.value;
                        }

                    }
                    output += '<tr><td></td><td>OUT OF ROUTE DISTANCE -</td><td>'+(totalDist/1000*0.621371).toFixed(0)+ ' mi</td></tr>';


                    document.getElementById('zip_code_output').innerHTML = '<table cellpadding="5">' + output + '</table>';
                }
            });
        }

        //FUNCTION TO LOAD THE GOOGLE MAPS API
        function loadScript() {
            var script  = document.createElement("script");
            script.type = "text/javascript";
            script.src  = "http://maps.googleapis.com/maps/api/js?key=AIzaSyCDZpAoR25KSkPTRIvI3MZoAg1NL6f0JV0&sensor=false&callback=initialize";
            document.body.appendChild(script);
        }

        window.onload = loadScript;

        </script>

Add the ids to form element and remove the quotation in array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.