473,765 Members | 2,001 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Time/distance converter help (ptII)

Further to my recent post in this newsgroup i've got to admit i'm
struggling. I've no experience with javascript or it's workings. What i'd
like is a simple converter to allow a user to input the distance travelled
in miles and the time in hours and minutes, the result being an average
speed. What i'd appreciate is for someone to write the script for me and
post here if possible. I am willing to learn but don't know where to start
and i've found no tutorial that will help me!

Thanks...Andre
Mar 3 '07 #1
11 4091
On Sat, 03 Mar 2007 22:10:04 +0100, Dirntknow <no****@please. comwrote:
Further to my recent post in this newsgroup i've got to admit i'm
struggling. I've no experience with javascript or it's workings. What i'd
like is a simple converter to allow a user to input the distance
travelled
in miles and the time in hours and minutes, the result being an average
speed. What i'd appreciate is for someone to write the script for me and
post here if possible. I am willing to learn but don't know where to
start
and i've found no tutorial that will help me!

Thanks...Andre

Assuming you want to run this script in a web page:

<html>
<head>
<title>Converti ng distance and time into speed</title>
<script type="text/javascript">
function Calculate() {
var theDistance = new Number(document .forms['theForm'].txtDistance.va lue);
var theTimeUsed = new Number(document .forms['theForm'].txtTimeUsed.va lue);
if(!NaN(theDist ance)&&!NaN(the TimeUsed)&&(the TimeUsed>0)) {
document.forms['theForm'].txtResult = (theDistance / (theTimeUsed/60));
return true;
}
return false;
}
</script>
</head>
<body>
<h1>Convertin g distance and time into speed</h1>
<form name="theForm" id="theForm" action="#" onsubmit="Calcu late();return
false;">
<fieldset><lege nd>Enter information:</legend>
<p><label for="txtDistanc e">Distance: <input type="text"
name="txtDistan ce" id="txtDistance " value="0" /(in miles).</label></p>
<p><label for="txtTimeUse d">Time Used: <input type="text"
name="txtTimeUs ed" id="txtTimeUsed " value="0" /(in minutes).</label></p>
</fieldset>
<fieldset><lege nd>Options</legend>
<p><input type="reset" value="Cancel" /<input type="submit"
value="Calculat e!" /></p>
</fieldset>
<fieldset><lege nd>Result</legend>
<p><label for="txtResult" >Average speed: <input type="text"
name="txtResult " id="txtResult" value="0" /(miles per hour).</p>
</fieldset>
</body>
</html>

--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
Mar 3 '07 #2
On Sat, 03 Mar 2007 22:26:34 +0100, OmegaJunior
<om*********@sp amremove.omegaj unior.netwrote:
On Sat, 03 Mar 2007 22:10:04 +0100, Dirntknow <no****@please. comwrote:
>Further to my recent post in this newsgroup i've got to admit i'm
struggling. I've no experience with javascript or it's workings. What
i'd
like is a simple converter to allow a user to input the distance
travelled
in miles and the time in hours and minutes, the result being an average
speed. What i'd appreciate is for someone to write the script for me and
post here if possible. I am willing to learn but don't know where to
start
and i've found no tutorial that will help me!

Thanks...And re


Assuming you want to run this script in a web page:

<html>
<head>
<title>Converti ng distance and time into speed</title>
<script type="text/javascript">
function Calculate() {
var theDistance = new
Number(document .forms['theForm'].txtDistance.va lue);
var theTimeUsed = new
Number(document .forms['theForm'].txtTimeUsed.va lue);
if(!NaN(theDist ance)&&!NaN(the TimeUsed)&&(the TimeUsed>0)) {
document.forms['theForm'].txtResult = (theDistance /
(theTimeUsed/60));
return true;
}
return false;
}
</script>
</head>
<body>
<h1>Convertin g distance and time into speed</h1>
<form name="theForm" id="theForm" action="#"
onsubmit="Calcu late();return false;">
<fieldset><lege nd>Enter information:</legend>
<p><label for="txtDistanc e">Distance: <input type="text"
name="txtDistan ce" id="txtDistance " value="0" /(in miles).</label></p>
<p><label for="txtTimeUse d">Time Used: <input type="text"
name="txtTimeUs ed" id="txtTimeUsed " value="0" /(in
minutes).</label></p>
</fieldset>
<fieldset><lege nd>Options</legend>
<p><input type="reset" value="Cancel" /<input type="submit"
value="Calculat e!" /></p>
</fieldset>
<fieldset><lege nd>Result</legend>
<p><label for="txtResult" >Average speed: <input type="text"
name="txtResult " id="txtResult" value="0" /(miles per hour).</p>
</fieldset>
</body>
</html>
Ack. Forgot </formbefore </body>.

--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
Mar 3 '07 #3
OmegaJunior <om*********@sp amremove.omegaj unior.netwrote:
<snip>
if(!NaN(theDist ance)&&!NaN(the TimeUsed)&&(the TimeUsed>0)) {
<snip ^^^^^^^^^^^^^^^ ^

Attempting to call a number is not going to be effective.

Richard.
Mar 3 '07 #4
On Sat, 03 Mar 2007 23:46:57 +0100, Richard Cornford
<Ri*****@litote s.demon.co.ukwr ote:
OmegaJunior <om*********@sp amremove.omegaj unior.netwrote:
<snip>
> if(!NaN(theDist ance)&&!NaN(the TimeUsed)&&(the TimeUsed>0)) {
<snip ^^^^^^^^^^^^^^^ ^

Attempting to call a number is not going to be effective.

Richard.
Erm, yeah. NaN() should be isNaN(). (Hope you meant to point that out.)
--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
Mar 3 '07 #5
Sorry, doesn't work for me!! :-(
Mar 4 '07 #6
Dirntknow wrote:
Further to my recent post in this newsgroup i've got to admit i'm
struggling. I've no experience with javascript or it's workings. What i'd
like is a simple converter to allow a user to input the distance travelled
in miles and the time in hours and minutes, the result being an average
speed. What i'd appreciate is for someone to write the script for me and
post here if possible. I am willing to learn but don't know where to start
and i've found no tutorial that will help me!
function getSpeed(distan ce,hours,minute s,precision){// distance: Miles
return toFixed(distanc e/(hours + minutes/60),precision?p recision:2) +"MPH";
}
However make sure user's input is valid, see discussion in an earlier
post by John Stockton.
Mick

Mick
Mar 4 '07 #7
On Mar 4, 7:10 am, "Dirntknow" <nos...@please. comwrote:
Further to my recent post in this newsgroup i've got to admit i'm
struggling. I've no experience with javascript or it's workings.
You probably wont find a single tutorial to teach you everything
that's needed, you'll need to learn about javascript in general then
apply the knowledge to problem.

You need to learn how to get values from form controls, validate the
input, display error messages, do calculations and format and present
the results.

The following should get you started, I've used an alert for the error
messages but it is much better to write them to the page in an
appropriate spot. I'll leave that to you:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<title>Units per Hour</title>
<style type="text/css">
.label {text-align: right;}
</style>

<script type="text/javascript">

// The following set of functions adds a toFixed method
// to the built-in Number object
// From clj FAQ: http://www.jibbering.com/faq/#FAQ4_6
function Stretch(Q, L, c) { var S = Q
if (c.length>0) while (S.length<L) { S = c+S }
return S
}
function StrU(X, M, N) { // X>=0.0
var T, S=new String(Math.rou nd(X*Number("1e "+N)))
if (S.search && S.search(/\D/)!=-1) { return ''+X }
with (new String(Stretch( S, M+N, '0')))
return substring(0, T=(length-N)) + '.' + substring(T)
}
function Sign(X) { return X<0 ? '-' : ''; }
function StrS(X, M, N) { return Sign(X)+StrU(Ma th.abs(X), M, N) }
Number.prototyp e.toFixed= function(n){ return StrS(this,1,n)} ;

// Check a possible float - decimal place is optional
function validNum(n) {
return /^\d+\.?\d*$/.test(n);
}

// Check an int
function validInt(n) {
return /^\d+$/.test(n);
}

// Convert units to per hour
function unitsPerHr(form ) {
var rate;
var dist = form.distance.v alue;
var time = form.time.value .split(':');
var hr = time[0];
var min = time[1];
var sec = time[2];
var err = [];

// Check distance is a valid number
if (!validNum(dist )) {
err.push('Quant ity must be a valid number, e.g. 23.5');
}

// Check time parts are valid
if (!validInt(hr) || !validInt(min) || !validNum(sec)) {
err.push('Time must be hour:min:sec, e.g. 2:23:15.5');
}

// Check time numbers are within range
if (min 59 || sec >= 60) {
err.push('Minut es and seconds must be less than 60');
}

// Convert time to decimal hours:
hr = +hr + min/60 + sec/3600;

if (hr 0) {
rate = (dist/hr).toFixed(2);
} else {
err.push('Time must be greater than zero')
}

if (err.length 0) {
alert(err.join( '\n\n'));
} else {
document.getEle mentById('resul t').innerHTML =
rate + ' units per hour';
}
return false;
}

</script>

<form action="" onsubmit="retur n unitsPerHr(this );">
<table>
<tr>
<td class="label">E nter quantity:
<td><input type="text" name="distance" value="0">
<tr>
<td class="label">E nter time<br>hr:min: sec:
<td><input type="text" name="time" value="0:0:0">
<tr>
<td class="label">< input type="submit" value="Calculat e">
<td><span id="result"></span>
</table>
</form>
--
Rob

Mar 4 '07 #8
Michael White wrote:
Dirntknow wrote:
>Further to my recent post in this newsgroup i've got to admit i'm
struggling. I've no experience with javascript or it's workings. What
i'd like is a simple converter to allow a user to input the distance
travelled in miles and the time in hours and minutes, the result being
an average speed. What i'd appreciate is for someone to write the
script for me and post here if possible. I am willing to learn but
don't know where to start and i've found no tutorial that will help me!
function getSpeed(distan ce,hours,minute s,precision){// distance: Miles
return toFixed(distanc e/(hours + minutes/60),precision?p recision:2) +"MPH";
}

That should be:
return (distance/(hours + minutes/60)).toFixed(pr ecision?precisi on:2)
+"MPH";
M
However make sure user's input is valid, see discussion in an earlier
post by John Stockton.
Mick

Mick
Mar 4 '07 #9
VK
toFixed(precisi on?precision:2)

That would prevent 0 signs in fraction, enforcing makeToFixed(0)
transformed to makeToFixed(2)
Unless it's a contextually useful default, one should prevent 0/false
ambiguousity by something like toFixed((typeof precision == 'number')?
precision:2)

Mar 4 '07 #10

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

Similar topics

20
3902
by: Xenophobe | last post by:
I have successfully converted the ASP code included in the following article to PHP: http://www.4guysfromrolla.com/webtech/040100-1.shtml As described the high and low latitudes and longitudes are pre-calculated and passed to the query. SELECT * FROM Locations
4
3815
by: Xenophobe | last post by:
I have successfully created a zip code radius search, but the performance is unacceptable. I have two tables. The first is 52K zip codes w/lat and long. The second is 3K national business addresses. Using the zip code 10010, it takes almost 60 seconds to return 122 businesses within a 25 mile radius. This slowdown is almost entirely due to the query radius distance formula.
8
524
by: Chris Dunaway | last post by:
When using a PropertyGrid, I have an object with a Date property, but I am only interested in the Time portion. How do I make the PropertyGrid allow editing the time only? Just the hours and minutes, preferably? Thanks -- Chris dunawaycsbcglobal_lunchmeat_net
3
1616
by: Benny | last post by:
Hi All, In an application I write, I need to have some mapping service, where I can select two locations, which shall calculate the distance and mainly the time(could be approximate) to travel from one place to another. Is there any ASP scripts or DLLs(APIs) provided or sold by any third party mapping service? Have anyone come across such requirments? Your experience and suggestions will help me much.
10
4735
by: Alan Johnson | last post by:
24.1.1.3 says about InputIterators: Algorithms on input iterators should never attempt to pass through the same iterator twice. They should be single pass algorithms. In 24.3.4.4 summarizes the effects of std::distance as: Effects: Returns the number of increments or decrements needed to get from first to last. The wording of the latter seems somewhat ambiguous. Does it mean that it actually performs the necessary increments or...
9
2323
by: nottheartistinquestion | last post by:
As an intellectual exercise, I've implemented an STL-esque List<and List<>::Iterator. Now, I would like a signed distance between two iterators which corresponds to their relative position in the list. For instance, if I did something like distance(list.end(), list.begin()), I would get -list.size(). The STL's iterator distance function amounts to something like this: distance_type distance(Iterator first, Iterator last) {...
1
4063
by: tiffrobe | last post by:
I'm a little lost on my program. Everything works fine except function 3. It gives out garbage numbers. Its suppose to give the distance between two points and then the area of 2 circles. #include <cmath> #include <string> #include <iostream> #include <fstream> #include <cstdlib> using namespace std;
11
6378
by: devnew | last post by:
hello while trying to write a function that processes some numpy arrays and calculate euclidean distance ,i ended up with this code (though i used numpy ,i believe my problem has more to do with python coding style..so am posting it here) .... # i am using these numpy.ndarrays to do the calculation facespace # of shape(totalimgs,imgpixels) weights # of shape(totalimgs,selectedfacespaces)
0
9568
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10160
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9951
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9832
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7378
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5275
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2805
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.