www.webdeveloper.com
Results 1 to 10 of 10

Thread: Calculation using some text boxes

  1. #1
    Join Date
    Jan 2011
    Posts
    22

    Unhappy Calculation using some text boxes

    hye..im new here..now, im doing my final year project..this is my page code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>
    <meta content="en-us" http-equiv="Content-Language" />
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>testing calculation</title>
    <style type="text/css">
    .style2 {
    text-align: left;
    }
    .style3 {
    font-family: "Bauhaus 93";
    font-size: xx-large;
    background-color: #C0C0C0;
    }
    </style>
    </head>

    <body style="background-color: #C0C0C0">

    <div class="style2">

    CAR CC:
    <input name="carcc" type="text" /><br />
    SPEED&nbsp;&nbsp;
    : <input name="speed" type="text" /><br />
    TRAVEL OCCURRENCES&nbsp;&nbsp;&nbsp; : <input name="occurrence" type="text" /><br />
    PASSENGERS: <input name="passenger" type="text" /><br />
    DISTANCE: <input name="distance" type="text" />
    </div>
    <form method="post">
    <div class="style2">
    <input name="submit" type="submit" value="CALCULATE RESULT" class="style3" /></div>
    </form>

    </body>

    </html>


    ..my problem now is i want to make a calculation for all the values in the text boxes and show the result under the CALCULATE RESULT button..my formula for this calculation is like this:
    [-20.955 + (0.0013 * carcc) + (0.1463 * speed) + (0.6766 * occurrence) + (0.04 * passenger) + (0.1481 * distance)]
    thanks for your help =)

  2. #2
    Join Date
    Jan 2011
    Posts
    9

    resolved

    Almost all you need is to add javascript to perform calculations.
    I have completely refactored the structure of your "calculator" and added some scripting. It works in all browsers since the old way of assigning events was used.
    Also, keep in mind that having markup, styles and scripts incorporated within the same document is a VERY bad manner.

    BTW, your markup is awful...=)
    Attached Files Attached Files

  3. #3
    Join Date
    Jan 2011
    Posts
    9

    resolved

    All in all as text:
    HTML Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    
        <head>
            <meta content="en-us" http-equiv="Content-Language"/>
            <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
            <title>testing calculation</title>
            <style type="text/css">
                body {
                    background-color: #C0C0C0;
                }
                #table-calc {
                    margin: 0 auto;
                    background-color: #e0e0e0;
                }
                #result-cell {
                    color: #ffffff;
                    font-weight: bold;
                    background-color: #333333;
                }
                .button {
                    font-family: "Bauhaus 93";
                    font-size: large;
                    background-color: #C0C0C0;
                }
            </style>
            <script type="text/javascript">
                window.onload = function() {
                    tableCalc = document.getElementById('table-calc');
                    resultCell = document.getElementById('result-cell');
                    button = document.getElementsByName('submit')[0];
                    button.onclick = calculate;
                }
                
                function calculate() {
                    var carcc = document.getElementsByName('carcc')[0].value;
                    var speed = document.getElementsByName('speed')[0].value;
                    var occurrence = document.getElementsByName('occurrence')[0].value;
                    var passenger = document.getElementsByName('passenger')[0].value;
                    var distance = document.getElementsByName('distance')[0].value;
    
                    var result = -20.955 + 0.0013*carcc + 0.1463*speed + 0.6766*occurrence + 0.04*passenger + 0.1481*distance;
                    
                    if (isNaN(result)) {
                        result = 'Incorrect value(s) entered!';
                    }
                    resultCell.innerHTML = result;
                }
            </script>
        </head>
    
        <body>
    
            <table id="table-calc" border="1" cellpadding="3">
                <tbody>
                    <tr>
                        <td>CAR CC</td>
                        <td>
                            <input name="carcc" type="text"/>
                        </td>
                    </tr>
                    <tr>
                        <td>SPEED</td>
                        <td>
                            <input name="speed" type="text"/>
                        </td>
                    </tr>
                    <tr>
                        <td>TRAVEL OCCURRENCES</td>
                        <td>
                            <input name="occurrence" type="text"/>
                        </td>
                    </tr>
                    <tr>
                        <td>PASSENGERS</td>
                        <td>
                            <input name="passenger" type="text"/>
                        </td>
                    </tr>
                    <tr>
                        <td>DISTANCE</td>
                        <td>
                            <input name="distance" type="text"/>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" align="center">
                            <input name="submit" type="submit" value="CALCULATE RESULT" class="button"/>
                        </td>
                    </tr>
                    <tr>
                        <td id="result-cell" colspan="2" align="center">[RESULT]</td>
                    </tr>
                </tbody>
            </table>
    
        </body>
        
    </html>

  4. #4
    Join Date
    Jan 2011
    Posts
    22
    XMLHttpRequest, sorry if my stail of markup is awful..im still learning..but thanks a lot coz u told me in an appropriate way..thanks again..=)

  5. #5
    Join Date
    Jan 2011
    Posts
    9
    no problem. if you have any questions on the script (or markup, or styles) - feel free to ask your question here.

  6. #6
    Join Date
    Jan 2011
    Posts
    22
    thanks..actually, i combined the calculation with google map..so, user dont have to key-in the distance..they will get the distance from the google map..

  7. #7
    Join Date
    Jan 2011
    Posts
    22
    hye..thanks for the advice earlier..i had made some arrangements in my coding and the style of my markup..hope u can give your opinion about my markup..and i also have some question(problems to ask)..below is my new coding for my system(sorry i tried to attach it but always come out in error)

    **currently, i have 3 problems for my system:
    1-for example, u type 'liverpool' in the 1st address and 'manchester' in the 2nd address.so, the result will be 'The distance between the two points on the chosen route is: 57.4 km'.so,i also want the '57.4' automatically shown on the DISTANCE text box.
    2-after you click the CALCULATE button, how can i make the result shown only in 2 decimal places.
    3-when i get the total from the calculation, how can i also make it automatically appear at the 'txtSterling' text box?

  8. #8
    Join Date
    Jan 2011
    Posts
    22

    Wink my current coding

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
    <title> MY CALCULATION</title>
    <meta name="description" content="Adds form content">
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <meta http-equiv="Content-Style-Type" content="text/css">
    <meta http-equiv="Content-Script-Type" content="text/javascript">

    <script type="text/javascript">
    var strCurrency=['Yen','US Dollar','Euro','Swiss Frank','Danish Korona'];
    var dblExchangeRate=[208.30, 1.99, 1.30, 2.06, 9.69];
    function convertCurrency(f){
    var txtS=f['txtSterling'];
    var selC=f['selCurrency'];
    var txtC=f['txtConversion'];
    txtC.value='';//reset to no value
    if(isNaN(txtS.value)){//validate for numbers
    txtS.value='';
    alert('Please insert a numerical value');
    txtS.focus();
    return;
    }
    var i=selC=f['selCurrency'].selectedIndex;
    txtC.value=(txtS.value*dblExchangeRate[i]).toFixed(2)+' '+strCurrency[i]
    }
    </script>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
    <script type="text/javascript">

    var location1;
    var location2;

    var address1;
    var address2;

    var latlng;
    var geocoder;
    var map;

    var distance;

    // finds the coordinates for the two locations and calls the showMap() function
    function initialize()
    {
    geocoder = new google.maps.Geocoder(); // creating a new geocode object

    // getting the two address values
    address1 = document.getElementById("address1").value;
    address2 = document.getElementById("address2").value;

    // finding out the coordinates
    if (geocoder)
    {
    geocoder.geocode( { 'address': address1}, function(results, status)
    {
    if (status == google.maps.GeocoderStatus.OK)
    {
    //location of first address (latitude + longitude)
    location1 = results[0].geometry.location;
    } else
    {
    alert("Geocode was not successful for the following reason: " + status);
    }
    });
    geocoder.geocode( { 'address': address2}, function(results, status)
    {
    if (status == google.maps.GeocoderStatus.OK)
    {
    //location of second address (latitude + longitude)
    location2 = results[0].geometry.location;
    // calling the showMap() function to create and show the map
    showMap();
    } else
    {
    alert("Geocode was not successful for the following reason: " + status);
    }
    });
    }
    }

    // creates and shows the map
    function showMap()
    {
    // center of the map (compute the mean value between the two locations)
    latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2);

    // set map options
    // set zoom level
    // set center
    // map type
    var mapOptions =
    {
    zoom: 1,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.HYBRID
    };

    // create a new map object
    // set the div id where it will be shown
    // set the map options
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    // show route between the points
    directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer(
    {
    suppressMarkers: true,
    suppressInfoWindows: true
    });
    directionsDisplay.setMap(map);
    var request = {
    origin:location1,
    destination:location2,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status)
    {
    if (status == google.maps.DirectionsStatus.OK)
    {
    directionsDisplay.setDirections(response);
    distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
    distance += "<br/>The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
    document.getElementById("distance_road").innerHTML = distance;
    }
    });

    // show a line between the two points
    var line = new google.maps.Polyline({
    map: map,
    path: [location1, location2],
    strokeWeight: 7,
    strokeOpacity: 0.8,
    strokeColor: "#FFAA00"
    });

    // create the markers for the two locations
    var marker1 = new google.maps.Marker({
    map: map,
    position: location1,
    title: "First location"
    });
    var marker2 = new google.maps.Marker({
    map: map,
    position: location2,
    title: "Second location"
    });

    // create the text to be shown in the infowindows
    var text1 = '<div id="content">'+
    '<h1 id="firstHeading">First location</h1>'+
    '<div id="bodyContent">'+
    '<p>Coordinates: '+location1+'</p>'+
    '<p>Address: '+address1+'</p>'+
    '</div>'+
    '</div>';

    var text2 = '<div id="content">'+
    '<h1 id="firstHeading">Second location</h1>'+
    '<div id="bodyContent">'+
    '<p>Coordinates: '+location2+'</p>'+
    '<p>Address: '+address2+'</p>'+
    '</div>'+
    '</div>';

    // create info boxes for the two markers
    var infowindow1 = new google.maps.InfoWindow({
    content: text1
    });
    var infowindow2 = new google.maps.InfoWindow({
    content: text2
    });

    // add action events so the info windows will be shown when the marker is clicked
    google.maps.event.addListener(marker1, 'click', function() {
    infowindow1.open(map,marker1);
    });
    google.maps.event.addListener(marker2, 'click', function() {
    infowindow2.open(map,marker1);
    });

    // compute distance between the two points
    var R = 6371;
    var dLat = toRad(location2.lat()-location1.lat());
    var dLon = toRad(location2.lng()-location1.lng());

    var dLat1 = toRad(location1.lat());
    var dLat2 = toRad(location2.lat());

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(dLat1) * Math.cos(dLat1) *
    Math.sin(dLon/2) * Math.sin(dLon/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;

    document.getElementById("distance_direct").innerHTML = "<br/>The distance between the two points (in a straight line) is: "+d;
    }

    function toRad(deg)
    {
    return deg * Math.PI/180;
    }
    </script>

    <style type="text/css">
    .style1 {
    text-align: center;
    }
    </style>

    </head>

    <script type="text/javascript">
    function calcTotalPub(theForm){
    var tempCc = theForm.elements['cc'].value;
    var tempFuel = theForm.elements['fuel'].value;
    var tempSpeed = theForm.elements['speed'].value;
    var tempDistance = theForm.elements['distance'].value;
    var tempTravel = theForm.elements['travel'].value;

    theForm.elements['txtTotal'].value = ( 1 - ( 2.7 - Number(tempFuel) ) / 2.7) * ( -20.846 +( Number(tempCc) * 0.013) +
    ( Number(tempSpeed) * 0.1462) + ( Number(tempDistance) * 0.148) -
    ( Number(tempTravel) * 0.6833) ) ;
    }
    </script>
    <body>
    <div id="form" style="width:100%; height:20%">
    <table align="center">
    <tr>
    <td colspan="7" align="center"><b>Find the distance between two
    locations</b></td>
    </tr>
    <tr>
    <td colspan="7">&nbsp;</td>
    </tr>
    <tr>
    <td>First address:</td>
    <td>&nbsp;</td>
    <td><input type="text" name="address1" id="address1" size="50"></td>
    <td>&nbsp;</td>
    <td>Second address:</td>
    <td>&nbsp;</td>
    <td><input type="text" name="address2" id="address2" size="50"></td>
    </tr>
    <tr>
    <td colspan="7">&nbsp;</td>
    </tr>
    <tr>
    <td colspan="7" align="center"><input type="button" value="Show" onclick="initialize();"></td>
    </tr>
    </table>
    </div>
    <center><div style="width:100%; height:10%" id="distance_direct"></div></center>
    <center><div style="width:100%; height:10%" id="distance_road"></div></center>

    <center><div id="map_canvas" style="width:70%; height:54%"></div></center>

    <h2 class="style1">WELCOME........</h2>
    <form name="Form1">
    <table id="table-calc" border="1" cellpadding="3">
    <tr>
    <td>CAR CC</td>
    <td>
    <input name="cc" type="text">
    </td>
    </tr>
    <tr>
    <td>FUEL PRICE</td>
    <td>
    <input name="fuel" type="text">
    </td>
    </tr>
    <tr>
    <td>SPEED</td>
    <td>
    <input name="speed" type="text">
    </td>
    </tr>
    <tr>
    <td>DISTANCE</td>
    <td>
    <input name="distance" type="text">
    </td>
    </tr>
    <tr>
    <td>TRAVEL OCCURRENCES</td>
    <td>
    <input name="travel" type="text">
    </td>
    </tr>
    <tr>
    <td>TOTAL</td>
    <td>
    <input type="text" name="txtTotal" value="00.00" readonly="readonly">

    <input type="button" value="CALCULATE" onclick="calcTotalPub(this.form);">
    <input type="reset" onclick="reset();">
    </td>
    </tr>


    </table>


    </form>
    <form action="">
    Your total: <input type="text" name="txtSterling" onblur="convertCurrency(this.form)">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    convert to
    <select name="selCurrency" onchange="convertCurrency(this.form)">
    <option>Yen</option>
    <option>US Dollars</option>
    <option>Euro</option>
    <option>Swiss Frank</option>
    <option>Danish Korona</option>
    </select>
    <input type="button" value="Convert" name="cmdCurrency" onclick="convertCurrency(this.form)">
    <input type="text" name="txtConversion" readonly="readonly">

    </form>

    </body>
    </html>

  9. #9
    Join Date
    Jan 2011
    Posts
    9

    resolved

    Quote Originally Posted by kidphantom View Post
    **currently, i have 3 problems for my system:
    1-for example, u type 'liverpool' in the 1st address and 'manchester' in the 2nd address.so, the result will be 'The distance between the two points on the chosen route is: 57.4 km'.so,i also want the '57.4' automatically shown on the DISTANCE text box.
    As far as I understand, the value may be received from google method as
    Code:
    response.routes[0].legs[0].distance.text
    Just add a variable containing this value and assign it as a 'value' property to the DISTANCE text box.
    Add code inside the 'directionsService.route' method.
    Quote Originally Posted by kidphantom View Post
    2-after you click the CALCULATE button, how can i make the result shown only in 2 decimal places.
    This is the correct rounding algorithm:
    Code:
    function round(n,dec) {
       if (!dec) {
          dec = 0; // round to integer if precision is not specified
       }
       var result = Math.round(n*Math.pow(10,dec))/Math.pow(10,dec);
       result.toFixed(dec);
       return result;
    }
    toFixed() and toPrecision() methods alone - will not do you any good: try dividing 10 by 3 using JavaScript, you'll see what I mean.
    Quote Originally Posted by kidphantom View Post
    3-when i get the total from the calculation, how can i also make it automatically appear at the 'txtSterling' text box?
    Firstly, I would recommend to optimize the whole structure of your calculator, so that you wouldn't need another text box.
    Secondly, use the 'value' property on the text boxes to get their values.

  10. #10
    Join Date
    Jan 2011
    Posts
    22
    thanks..i will try to solve the 2nd problem..btw, can u show me the example such my 1st problem?its ok if u use different example and do not use my coding..

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles