473,503 Members | 5,382 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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="Calculate" onclick="fuelCalculator();" />

</form>

</body>

</html>

Jan 24 '06 #1
8 4232
rd********@gmail.com wrote:
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.
You should say what you think is going wrong - error messages, results, etc.

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.
[...]
<SCRIPT LANGUAGE = "JavaScript">
The language attribute is deprecated, type is required.

<script type="text/javascript">
function fuelCalculator() {
var costpergallon;
costpergallon= document.form1.ppg.value / document.form1.mpg.value;
document.form1.cpg.value = costpergallon;
document.write(costpergallon);
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

}
</ script>

Typo?

</script>

[...]
--
Rob
Jan 24 '06 #2
<rd********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
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="Calculate" onclick="fuelCalculator();" />
</form>
</body>
</html>


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

Jan 24 '06 #3
Honestly , you code should be as follows:

<HTML>

<HEAD>

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

<SCRIPT LANGUAGE = "JavaScript">

function fuelCalculator() {
var iPPG = document.getElementById("ppg").value ;
var iMPG = document.getElementById("mpg").value ;
document.getElementById("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="fuelCalculator();">Calculate</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().

Jan 24 '06 #4
Zif
jg*****@gmail.com wrote:
Honestly , you code should be as follows:
Honestly, don't.


<HTML>

<HEAD>

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

<SCRIPT LANGUAGE = "JavaScript">
The language attribute is deprecated whereas the type attribute is required.

<SCRIPT type="javascript">

function fuelCalculator() {
var iPPG = document.getElementById("ppg").value ;
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.

var iMPG = document.getElementById("mpg").value ;
document.getElementById("cpg").value = parseFloat(iPPG) /
parseFloat(iMGP) ;
Don't allow auto-wrapping to wrap code, it will almost certainly
introduce errors.

}

</ script>
</head>
<Body>

<input type="text" id="ppg" value=0 /> </br>
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).

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

<button onclick="fuelCalculator();">Calculate</button>
The default type for a button element is submit, so that should be:

<button type="button" onclick="fuelCalculator();">Calculate</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.

</body>

</html>

Unless you're submitting the form you don't need the <form /> tag and
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="Calculate"
onclick="fuelCalculator(this.form);"></td>
</tr>
</table>
</form>

the old <input type=button" /> is slightly out dated as well. Remember
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.

with js all vars are objects, you need to hint to the engine what you
want it to do with them; hence parseFloat().


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
Jan 24 '06 #5
Zif
Zif wrote:
jg*****@gmail.com wrote:

[...]
<SCRIPT LANGUAGE = "JavaScript">


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

<SCRIPT type="javascript">


Yeah, right...

<SCRIPT type="text/javascript">

[...]
--
Zif
Jan 24 '06 #6
Zif said the following on 1/24/2006 1:10 AM:
jg*****@gmail.com wrote:
Honestly , you code should be as follows:
Honestly, don't.


100% Agreed.

var iPPG = document.getElementById("ppg").value ;
var iMPG = document.getElementById("mpg").value ;
document.getElementById("cpg").value = parseFloat(iPPG) /
parseFloat(iMGP) ;

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


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

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jan 24 '06 #7
JRS: In article <11**********************@g47g2000cwa.googlegroups .com>
, dated Mon, 23 Jan 2006 20:07:26 remote, seen in
news:comp.lang.javascript, jg*****@gmail.com posted :
the old <input type=button" /> is slightly out dated as well.


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 <ln************@nuthaus.mib.org> :-
If you want to post a followup via groups.google.com, 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.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jan 25 '06 #8
Dr John Stockton said the following on 1/25/2006 12:30 PM:
JRS: In article <11**********************@g47g2000cwa.googlegroups .com>
, dated Mon, 23 Jan 2006 20:07:26 remote, seen in
news:comp.lang.javascript, jg*****@gmail.com posted :
the old <input type=button" /> is slightly out dated as well.


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.


<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.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jan 25 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3296
by: Alexander Ross | last post by:
I am trying to create a simple mail form (i.e. five fields, the users pushes send and using the mail function I get an email with their input values). The problem is that some people will be...
1
2479
by: Mattia | last post by:
Hi! I would like to validate a fiels in a form, but the code I wrote doesn't seem to work: HTML: <form name="formNome" method="post" action="/index.php" onSubmit="return...
3
11857
by: David N | last post by:
Hi All, I just wonder if in C#, I can develop a user defined control that can call its parent function which is not yet developed. For example, how do I make my user control call a...
4
7055
by: bob lambert | last post by:
Help I am trying to deploy to another pc a vb.net std 2002 windows form application. I am confused. I created a project - windows form I built form, compiled and debugged. I created a...
1
1441
by: VictorT | last post by:
Hi All, I am trying to create a simple Windows form that lists a users' data one user at a time with the usual "Next" & "Previous" buttons. Upon loading the form, I am able to populate all...
2
6143
by: strasth | last post by:
i'm student from malaysia need some guide to solve my problem in oracle. my problem is how to make simple calculation in oracle. for example to make addition in two data. in PHP i only paste the...
14
2767
by: ap.sakala | last post by:
Hello, How the heck should I make this simple summering of a data without a submit button? Like in an excel sheet I would like to have a couple of cells in a column and as soon the visitor...
3
1405
by: Rando | last post by:
Hello All! First of all, Great forums! Now my question: For a site I've to make an simple calculation forum, only I don't really know how to do so. This is what the script should do: Y =...
1
2603
by: dan.cawthorne | last post by:
Hi all, Need Some Help With A Simple Password Form What a I Have Is Single Field Table, With One Record In It The Field is Called table is also called "Password" which ive created a form...
0
7193
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7067
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
6975
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7449
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5562
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4992
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3160
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
1
728
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
371
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.