Simple Calculation in Form - 3 textboxes - 1 function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • rdavis7408@gmail.com

    Simple Calculation in Form - 3 textboxes - 1 function

    I am attempting what I would think would be a simple calculation of the
    cost of traveling a single mile. But I can not figure this out. The
    following is my script. Any help would be appreciated.

    I want the user to enter the price per gallon in one textbox, the miles
    per gallon in the next textbox and then press the button and get the
    cost per gallon by dividing the price per gallon by the miles per
    gallon.


    Thank you in advance
    <HTML>

    <HEAD>

    <TITLE> "CALCULATE FUEL COST" </TITLE>



    <SCRIPT LANGUAGE = "JavaScript ">


    function fuelCalculator( ) {
    var costpergallon;
    costpergallon= document.form1. ppg.value / document.form1. mpg.value;
    document.form1. cpg.value = costpergallon;
    document.write( costpergallon);
    }


    </ script>
    </head>
    <Body>
    <form name ="form1">

    <input type="text" name="ppg" value=0 /> </br>
    <input type="text" name="mpg" value=0 /> </br>
    <input type="text" name="cpg" value=0 /> </br>

    <input type= "button" value="Calculat e" onclick="fuelCa lculator();" />



    </form>

    </body>

    </html>

  • RobG

    #2
    Re: Simple Calculation in Form - 3 textboxes - 1 function

    rdavis7408@gmai l.com wrote:[color=blue]
    > I am attempting what I would think would be a simple calculation of the
    > cost of traveling a single mile. But I can not figure this out. The
    > following is my script. Any help would be appreciated.[/color]

    You should say what you think is going wrong - error messages, results, etc.

    [color=blue]
    > I want the user to enter the price per gallon in one textbox, the miles
    > per gallon in the next textbox and then press the button and get the
    > cost per gallon by dividing the price per gallon by the miles per
    > gallon.
    >[/color]
    [...][color=blue]
    >
    > <SCRIPT LANGUAGE = "JavaScript ">[/color]

    The language attribute is deprecated, type is required.

    <script type="text/javascript">
    [color=blue]
    > function fuelCalculator( ) {
    > var costpergallon;
    > costpergallon= document.form1. ppg.value / document.form1. mpg.value;
    > document.form1. cpg.value = costpergallon;
    > document.write( costpergallon);[/color]

    document.write will completely replace the content of the document with
    the value of costpergallon. Just get rid of that line.

    Also be aware that the values of text inputs are type string. Because
    you are using division, they are automatically converted to numbers for
    the calculation and costpergallon will be a type number (the same
    happens with multiplication and division too).

    If attempting addition, strings will be concatenated:

    var x='1', y='2'; // x and y are strings
    alert(x + y) // shows 12 - x & y concatenated
    alert(x / y) // shows 0.5 - x divided by y
    alert(x + y) // shows 12 - x & y are still strings

    To make x & y numbers for the sake of addition, use the unary '+' operator:

    alert(+x + +y) // shows 3 - x & y added


    Or double subtraction:

    alert(x - -y) // shows 3 - x & y added

    [color=blue]
    > }
    >
    >
    > </ script>[/color]


    Typo?

    </script>

    [...]


    --
    Rob

    Comment

    • McKirahan

      #3
      Re: Simple Calculation in Form - 3 textboxes - 1 function

      <rdavis7408@gma il.com> wrote in message
      news:1138070925 .693797.319560@ f14g2000cwb.goo glegroups.com.. .[color=blue]
      > I am attempting what I would think would be a simple calculation of the
      > cost of traveling a single mile. But I can not figure this out. The
      > following is my script. Any help would be appreciated.
      >
      > I want the user to enter the price per gallon in one textbox, the miles
      > per gallon in the next textbox and then press the button and get the
      > cost per gallon by dividing the price per gallon by the miles per
      > gallon.
      >
      >
      > Thank you in advance
      > <HTML>
      > <HEAD>
      > <TITLE> "CALCULATE FUEL COST" </TITLE>
      > <SCRIPT LANGUAGE = "JavaScript ">
      > function fuelCalculator( ) {
      > var costpergallon;
      > costpergallon= document.form1. ppg.value / document.form1. mpg.value;
      > document.form1. cpg.value = costpergallon;
      > document.write( costpergallon);
      > }
      > </script>
      > </head>
      > <Body>
      > <form name ="form1">
      > <input type="text" name="ppg" value=0 /> </br>
      > <input type="text" name="mpg" value=0 /> </br>
      > <input type="text" name="cpg" value=0 /> </br>
      > <input type= "button" value="Calculat e" onclick="fuelCa lculator();" />
      > </form>
      > </body>
      > </html>[/color]

      What the difference between "price per gallon" and "cost per gallon"?

      Your code works under IE5.5 -- at least the math...

      However,
      a) It should be: "text/javascript">
      b) you have a space in "</ script>".
      c) what "document.write (costpergallon) ;"?
      d) you don't round the result.
      e) labels for the input fields would help!
      f) you might want to use "parseFloat ()".

      BTW, people don't usually know how many miles per gallon
      they get!

      The cost per gallon is what one pays at the pump.

      I note the cost to fill up and the mileage; when I fill it up again
      I note the mileage then calculate the mileage difference and divide
      that into the cost I paid to fill it up. For example:

      Ending mileage: 10,200
      Starting mileage: 10,000
      Difference: 200

      Cost to fill up: $50.00
      Gals. to fill up: 20

      Cost per mile: $50.00 / 200 = $0.25



      Comment

      • jgwyman@gmail.com

        #4
        Re: Simple Calculation in Form - 3 textboxes - 1 function

        Honestly , you code should be as follows:

        <HTML>

        <HEAD>

        <TITLE> "CALCULATE FUEL COST" </TITLE>

        <SCRIPT LANGUAGE = "JavaScript ">

        function fuelCalculator( ) {
        var iPPG = document.getEle mentById("ppg") .value ;
        var iMPG = document.getEle mentById("mpg") .value ;
        document.getEle mentById("cpg") .value = parseFloat(iPPG ) /
        parseFloat(iMGP ) ;
        }

        </ script>
        </head>
        <Body>

        <input type="text" id="ppg" value=0 /> </br>
        <input type="text" id="mpg" value=0 /> </br>
        <input type="text" id="cpg" value=0 /> </br>

        <button onclick="fuelCa lculator();">Ca lculate</button>


        </body>

        </html>

        Unless you're submitting the form you don't need the <form /> tag and
        the old <input type=button" /> is slightly out dated as well. Remember
        with js all vars are objects, you need to hint to the engine what you
        want it to do with them; hence parseFloat().

        Comment

        • Zif

          #5
          Re: Simple Calculation in Form - 3 textboxes - 1 function

          jgwyman@gmail.c om wrote:[color=blue]
          > Honestly , you code should be as follows:[/color]

          Honestly, don't.

          [color=blue]
          >
          > <HTML>
          >
          > <HEAD>
          >
          > <TITLE> "CALCULATE FUEL COST" </TITLE>
          >
          > <SCRIPT LANGUAGE = "JavaScript ">[/color]

          The language attribute is deprecated whereas the type attribute is required.

          <SCRIPT type="javascrip t">

          [color=blue]
          > function fuelCalculator( ) {
          > var iPPG = document.getEle mentById("ppg") .value ;[/color]

          Support for DOM methods should be tested before attempting to use them.
          The forms collection is more widely supported and is probably better
          to use here.

          [color=blue]
          > var iMPG = document.getEle mentById("mpg") .value ;
          > document.getEle mentById("cpg") .value = parseFloat(iPPG ) /
          > parseFloat(iMGP ) ;[/color]

          Don't allow auto-wrapping to wrap code, it will almost certainly
          introduce errors.

          [color=blue]
          > }
          >
          > </ script>
          > </head>
          > <Body>
          >
          > <input type="text" id="ppg" value=0 /> </br>[/color]

          XHTML-style tags are invalid markup in an HTML document.

          <input type="text" id="ppg" value=0><br>


          XHTML requires all tag and attribute names to be in lower case (but this
          isn't XHTML so it's of no consequence).

          [color=blue]
          > <input type="text" id="mpg" value=0 /> </br>
          > <input type="text" id="cpg" value=0 /> </br>
          >
          > <button onclick="fuelCa lculator();">Ca lculate</button>[/color]

          The default type for a button element is submit, so that should be:

          <button type="button" onclick="fuelCa lculator();">Ca lculate</button>


          It likely makes no difference outside a form, but it should be included
          as the button may find its way into a form (the OP has shown a
          preference to use a form) where its default type of submit will cause a
          problem.

          [color=blue]
          > </body>
          >
          > </html>
          >
          > Unless you're submitting the form you don't need the <form /> tag and[/color]

          A form element isn't necessary but document.forms is more widely
          supported than getElementById. It is also easier to use to get
          references to form controls than using getElementById to get references
          to random elements.

          e.g.

          <script type="text/javascript">
          function fuelCalculator( f)
          {
          f.cpg.value = f.ppg.value/f.mpg.value;
          }
          </script>

          <form action="">
          <table>
          <tr>
          <td>Cents per gallon:</td>
          <td><input type="text" name="ppg" value=0></td>
          </tr><tr>
          <td>Miles per gallon:</td>
          <td><input type="text" name="mpg" value=0></td>
          </tr><tr>
          <td>Cents per mile:</td>
          <td><input type="text" name="cpg" value=0></td>
          </tr><tr>
          <td colspan="2" style="text-align:right;">< input type="button"
          value="Calculat e"
          onclick="fuelCa lculator(this.f orm);"></td>
          </tr>
          </table>
          </form>

          [color=blue]
          > the old <input type=button" /> is slightly out dated as well. Remember[/color]

          The only real difference between a button element and an input element
          type button is that buttons can have content, inputs can't. The OP has
          not indicated any requirement for content, so the use of a button is not
          indicated.

          I don't think there is any intent to deprecate input type button so it
          is no more out of date than most other HTML elements.

          [color=blue]
          > with js all vars are objects, you need to hint to the engine what you
          > want it to do with them; hence parseFloat().[/color]

          It is a good suggestion to validate input, however parseInt & parseFloat
          are pretty useless for that. Their primary purpose seems to be to remove
          trailing non-digit characters (such as units) from strings and return
          numbers.

          e.g.
          parseInt('25mpg ') returns '25' as type number
          parseInt('2mpg5 ') returns '2' as type number



          --
          Zif

          Comment

          • Zif

            #6
            Re: Simple Calculation in Form - 3 textboxes - 1 function

            Zif wrote:[color=blue]
            > jgwyman@gmail.c om wrote:[/color]
            [...][color=blue][color=green]
            >> <SCRIPT LANGUAGE = "JavaScript ">[/color]
            >
            > The language attribute is deprecated whereas the type attribute is
            > required.
            >
            > <SCRIPT type="javascrip t">[/color]

            Yeah, right...

            <SCRIPT type="text/javascript">

            [...]


            --
            Zif

            Comment

            • Randy Webb

              #7
              Re: Simple Calculation in Form - 3 textboxes - 1 function

              Zif said the following on 1/24/2006 1:10 AM:[color=blue]
              > jgwyman@gmail.c om wrote:[color=green]
              >> Honestly , you code should be as follows:[/color]
              >
              > Honestly, don't.[/color]

              100% Agreed.

              [color=blue][color=green]
              >> var iPPG = document.getEle mentById("ppg") .value ;
              >> var iMPG = document.getEle mentById("mpg") .value ;
              >> document.getEle mentById("cpg") .value = parseFloat(iPPG ) /
              >> parseFloat(iMGP ) ;[/color][/color]
              [color=blue]
              > Don't allow auto-wrapping to wrap code, it will almost certainly
              > introduce errors.[/color]

              As will parseFloat in that instance. Unary + is more efficient at
              converting strings to Number than parseFloat is.

              --
              Randy
              comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
              Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/

              Comment

              • Dr John Stockton

                #8
                Re: Simple Calculation in Form - 3 textboxes - 1 function

                JRS: In article <1138075646.885 125.297490@g47g 2000cwa.googleg roups.com>
                , dated Mon, 23 Jan 2006 20:07:26 remote, seen in
                news:comp.lang. javascript, jgwyman@gmail.c om posted :
                [color=blue]
                >the old <input type=button" /> is slightly out dated as well.[/color]

                Javascript in Web pages is executed on the customers' machines, not the
                author's. Therefore, traditional constructs should not be replaced by
                new-fangled ones until an adequate preponderance of user systems will
                understand them.




                If you find that, when you start a News reply, Google does not provide
                the previous article in quoted form, note what Keith Thompson wrote in
                comp.lang.c, message ID <lnwtuhfy7d.fsf @nuthaus.mib.or g> :-
                If you want to post a followup via groups.google.c om, don't use
                the "Reply" link at the bottom of the article. Click on "show
                options" at the top of the article, then click on the "Reply" at
                the bottom of the article headers.

                Since that is what the experts in this newsgroup prefer to read, it will
                be to your advantage to comply. Read the FAQ.

                --
                © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                Comment

                • Randy Webb

                  #9
                  Re: Simple Calculation in Form - 3 textboxes - 1 function

                  Dr John Stockton said the following on 1/25/2006 12:30 PM:[color=blue]
                  > JRS: In article <1138075646.885 125.297490@g47g 2000cwa.googleg roups.com>
                  > , dated Mon, 23 Jan 2006 20:07:26 remote, seen in
                  > news:comp.lang. javascript, jgwyman@gmail.c om posted :
                  >[color=green]
                  >> the old <input type=button" /> is slightly out dated as well.[/color]
                  >
                  > Javascript in Web pages is executed on the customers' machines, not the
                  > author's. Therefore, traditional constructs should not be replaced by
                  > new-fangled ones until an adequate preponderance of user systems will
                  > understand them.[/color]

                  <button> is a "new-fangled" construct? Surely you jest.

                  A more appropriate statement would be along the lines of:

                  "Do not constrain yourself to antiquated HTML habits based on 1 or 2
                  peoples inability to update."

                  --
                  Randy
                  comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
                  Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/

                  Comment

                  Working...