STUDENT - Javascript Problem

goldy300

New Member
Messages
33
Reaction score
0
Points
0
I've been going through a few exercises and displaying the result on another page using document.write. I actually want to display the result in the text box at the bottom after the user hits the button. so onClick or onSubmit but I don't know how to display the total in that box.

I always appreciate your help guys!

HTML:
<HTML>
<HEAD>
<TITLE> Car ownership costs </TITLE>


<script type="text/javascript">
function calculate()
{
document.form1.calculate.value = (document.form1.rego.value) + (document.form1.pink.value) + (document.form1.green.value) + (document.form1.insure.value) + (document.form1.rsfee.value) + ((document.form1.petorl.value)*52) + (document.form1.tyre.value) + (document.form1.fines.value) + ((document.form1.service.value)*2);



}
</script>

</HEAD>
<BODY bgcolor="#4809c7">
<font color="#ffffff" face="arial"><center><h1>Car Ownership Costs</h1></center>
<form name="form1">
<center>
<table border="0" cellpadding="10" bgcolor="white" cellspacing="0">
<tr>
    <td colspan="2" bgcolor="#d7d7d7"><center>Anual Costs<br></center></td>
</tr>
<tr>
    <td>Car Registration:</td><td><input name="rego" size="5"> per year</td>
</tr>
<tr>
    <td>Pink Slip:</td><td><input name="pink" size="5"> per year</td>
</tr>
<tr>
    <td>Green Slip:</td><td><input name="green" size="5"> per year</td>
</tr>
<tr>
    <td>Comprehensive Insurance:</td><td><input name="pink" size="5"> per year</td>
</tr>
<tr>
    <td>Road Service Fee:</td><td><input name="rsfee" size="5"> per year</td>
</tr>
<tr>
    <td>Green Slip:</td><td><input name="green" size="5"> per year</td>
</tr>
<tr><td colspan="2" bgcolor="#d7d7d7"><center>Variable Costs</center></td></tr>

<tr>
    <td>Petrol:</td><td><input name="rego" size="5"> per week</td>
</tr>
<tr>
    <td>Tyre Replacement:</td><td><input name="tyre" size="5"> per year</td>
</tr>
<tr>
    <td>Speeding fines:</td><td><input name="fines" size="5"> per year</td>
</tr>
<tr>
    <td>Car Service:</td><td><input name="service" size="5"> per 6 months</td>
</tr>
<tr>
    <td><input type="button" value="Calculate Total" name="calculate" onClick="calculate()"></td><!--This must be wrong-->
    <td>$ <input ??total cost here??    </td><!-- I have no idea on how to display the total in a text box -->
</tr>

</table>
</center>
</form>
</font>
</BODY>
</HTML>

Thanks again.
 

xmakina

New Member
Messages
264
Reaction score
0
Points
0
Use AJAX to redraw the text box. Set it's value attribute to the calculated total.

Also - Google will provide you with an answer faster than these forums :)
 

goldy30

New Member
Messages
60
Reaction score
0
Points
0
Use AJAX to redraw the text box. Set it's value attribute to the calculated total.

Also - Google will provide you with an answer faster than these forums :)


I understand that but I have no one from google who can comment on my code if there is something else wrong... what is AJAX?
 

xmakina

New Member
Messages
264
Reaction score
0
Points
0
No. Nor will you always have access to a community that can help. That's why you must learn to understand the debugger and see your own mistakes.

It's also a damn sight faster when you can spot the bug straight away.

Go learn ajax at w3schools. Or just, again, google it.
 

Salvatos

Member
Prime Account
Messages
562
Reaction score
1
Points
18
I didn't really look at your code but give a name to your input, whatever it is (nameHere in my example) and put something like this in your JS:
document.postForm.nameHere.value= the value you want to display.

As I said I didn't really look at your code but it should give you the basic idea. I just copied and pasted it from ProBoards' "characters remaining" script.
 

goldy30

New Member
Messages
60
Reaction score
0
Points
0
Isn't the purpose of this section of the forum to post your javascript problems???

Because I'm learning and don't completely know javascript, I don't always know what I'm looking for to debug... I'm behind but catching up on old work while it's the holidays. I don't have my teacher around to explain things to me so I post my problems here. Normally it's quite helpful.

Telling me to go else where to learn is kind of weird considering they want people to visit and post things here in the forum.

Can anyone else help?
Edit:
I have this already though.

function calculate()

document.form1.calculate.value = blah....

In the form, in the input I have

<input type="button" value="Calculate Total" name="calculate"></td> <!-- should I put onSubmit or onClick="calculate()" in here? -->

But in the other input where it's a text field, I want to show the value. How do I write it so the button calls the function and displays it in the other <input name="" size="10"> ???

I've swapped it around several ways but it'd be something I don't know about. I can't find anything on google the same as what I want to do.
 
Last edited:

natsuki

New Member
Messages
112
Reaction score
0
Points
0
You don't really need to use AJAX on this one as simple javascript can do the trick. You can change the text in a textbox/div or anything at all with a button click or just any other event.

I needed to save your code and load it on my own just to find out the erros. It could have been better if you wrapped some of the code, especially the javascript. Heres a tip: use around 80 columns and wrap the remaining code on a new line. It's also what most programmers do.

Now, you had redudant names in your input boxes, that's ambiguous. A name should be as unique as an id especially if you're gonna use it to get values. What do you think would happen if you have green = document.form1.green.value;? Since there are 2 boxes with the name "green", javascript won't know which one you are asking for, and that complicates things for you and javascript. ;p You should use meaningful names for your boxes. In your function you were using insure.value, but in your html it was named "pink", why didn't you just name it as insure as that would have been meaningful? And you were using a name ("insure") which is not even existent in your html code anyway.

HTML:
....<td><input name="insure" size="5" /></td><!-- rename all the other redundant ones, putting a closing tag "/>" at the end of an empty tag (like input) is recommended instead of ">" -->
....
<tr>
    <td><input type="button" value="Calculate Total" name="calculate" onclick="calc();" /></td>
<!-- calculate() apparently isn't working, it seems that it's a reserved javascript word, just use another name or change it's case (ex. Calculate()) -->
    <td><input name="total" type="text" value="$ 0.00" /></td>
<!-- Total i think would be a better name for it. You can even use any element like a div/span/etc -->
</tr>
and then on the script start to practice organizing your code a bit, you'll have an easier time if you put them first in variables so you can easily use them later. And as a student, you'll have an easier time understanding code by doing so.
Code:
// calculate() doesn't seem to work, probably a reserved keyword
// used a different name:
function calc()
{
    var rego, pink, insure, ...blah;
    var total;

    rego = toNum(document.form1.rego.value);
    pink = toNum(blah);
    insure = toNum(document.form1.insure.value);
    ...
    total = rego + pink + blah...;

    document.form1.total.value = "$ " + total;
...
then have a function that checks if the values entered are actually numbers or 0 if not a number (NaN) because if you use + right on you'll end up concatenating the values instead of adding them because they are actually strings ("1" + "1" = "11" and not 2). parseFloat() seems to a better option than Number().

Code:
function toNum(str)
{
    return (isNaN(str) || str == "") ? 0 : parseFloat(str);
}
I think you need to study some more, also, you are using some deprecated tags and attributes that are now supposed to be done using CSS. And your page is in quirks mode (displays page as if it was from an older browser). You ought to turn it to standard compliance mode. You can do that by adding a DOCTYPE declaration at the very top of the html page.
ex:
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" lang="en">
<head>...
There are many kinds of doctypes but this one I like the most. Also note that what you are actually using is NOT HTML but rather XHTML. If you wan't to know more just w3school or google.

I wanted to impart this bits of info to you earlier on so that you can go on with what you are learning as a student whilst making well-formed code. You may however wish to ignore this stuffs for now. It might me too much for you to understand, but it's better you learn this stuff already as you'll eventually need it anyway.^^

EDIT: you can see the code in action here: http://kiddragon.co.cc/test/costs.html I used regular expression for checking the number instead, only numbers 0.124, 11.024, 124 etc are valid everything else it will evaluate to 0 (including -1 etc and 1e20) You had 2 green slip fields I just removed one. You can look at the source code but try to do it on your own.
 
Last edited:

goldy30

New Member
Messages
60
Reaction score
0
Points
0
Yeah the pink thing had to do with pinkslips for car registration that was obviously something I'd overlooked but yeah. I did know about parseFloat, a mate just told me about the other day.... and the doctype I just didn't include. My editor automatically puts it in.

But I see now how you have used onClick with calc, created variables from the names in the form and a total where the math is done... then you gave $0.00 value to the text box and the total calls the math into it... see it was simple. I'll remember that. Thanx Natsuki
 

natsuki

New Member
Messages
112
Reaction score
0
Points
0
no prob^^
just remember to always do a check of the inputted values if they are really numbers or blah
 

goldy30

New Member
Messages
60
Reaction score
0
Points
0
I understand everything that you've done but this I don't quite get.

function toNum(str)
{
var p = /^[0-9]*\.?[0-9]+\s*$/; // a better number check can be done using regexp
return p.test(str) ? parseFloat(str) : 0;
//return (isNaN(str) || str == "") ? 0 : parseFloat(str);
}
 

Twinkie

Banned
Messages
1,389
Reaction score
12
Points
0
Again, didn't look at your code but you should include spaces in between operators to make it easier too read. I think that mathematical expression just gave me a headache.
 

dickey

New Member
Messages
128
Reaction score
0
Points
0
Just an advice try to make your code readable create your own set of rules like how many spaces to indent block level codes.

I use 2 spaces:

so basically my html template would look like this

HTML:
<html>
  <head>
    <title>title goes here!</title>
    <script type='text/scripttype'>
       lines of code...
    </script>  
  </head>
......

now regarding your problem I think as someone mentioned you used some names twice and an input box for the green slip appeared twice.

Now regarding the conversion to float. you don't need to create a new function just add parseFloat in front of your formulas.

HTML:
 <script type="text/javascript">
    //I keep wondering why if I used calculate() browsers don't work properly. can someone checK
    function calculat()
    {
      frm1=document.form1;
      frm1.total.value = parseFloat(frm1.rego.value) + 
                         parseFloat(frm1.pink.value) + 
                         parseFloat(frm1.green.value) + 
                         parseFloat(frm1.insure.value) + 
                         parseFloat(frm1.rsfee.value) + 
                         parseFloat((frm1.petrol.value)*52) + 
                         parseFloat(frm1.tyre.value) + 
                         parseFloat(frm1.fines.value) + 
                         parseFloat((frm1.service.value)*2);
    }
</script>

now isn't that more appealing to the eyes?

oh you might wonder where "document.form1.total.value" came from?

I added a text input at the bottom of your code just below the submit button.

HTML:
<input type='text' name='total' readonly />

*another note as you may have noticed I closed the input box with '/>' instead of the normal '>' It is to adhere to w3 standards though you may use '>' as you like. I like my pages to be "W3 Compliant" so don't get confused.
 
Last edited:

natsuki

New Member
Messages
112
Reaction score
0
Points
0
I understand everything that you've done but this I don't quite get.

function toNum(str)
{
var p = /^[0-9]*\.?[0-9]+\s*$/; // a better number check can be done using regexp
return p.test(str) ? parseFloat(str) : 0;
//return (isNaN(str) || str == "") ? 0 : parseFloat(str);
}
this one I explained already in PM

It seems I share the same principles with the other posters regarding code organization.^^
 

Jordan C

New Member
Messages
433
Reaction score
0
Points
0
Sorry if it's already answered. I spent quite a lot of time working on it.

HTML:
<HTML>
<HEAD>
<TITLE> Car ownership costs </TITLE>


<script type="text/javascript">
function cal(){
petrol = 52 * document.form1.petrolwk.value
service = 2 * document.form1.service6m.value
rego = document.form1.rego.value
pink = document.form1.pink.value
green = document.form1.green.value
insu = document.form1.insu.value
rsfee = document.form1.rsfee.value
tyre = document.form1.tyre.value
fines = document.form1.fines.value
answer = petrol*1 + service*1 + rego*1 + pink*1 + green*1 + insu*1 + rsfee*1 + tyre*1 + fines*1
document.form1.answerbox.value = answer
}
</script>

</HEAD>
<BODY bgcolor="#4809c7">
<font color="#ffffff" face="arial"><center><h1>Car Ownership Costs</h1></center>
<form name="form1">
<center>
<table border="0" cellpadding="10" bgcolor="white" cellspacing="0">
<tr>
    <td colspan="2" bgcolor="#d7d7d7"><center>Anual Costs<br></center></td>
</tr>
<tr>
    <td>Car Registration:</td><td><input name="rego" size="5"> per year</td>
</tr>
<tr>
    <td>Pink Slip:</td><td><input name="pink" size="5"> per year</td>
</tr>
<tr>
    <td>Green Slip:</td><td><input name="green" size="5"> per year</td>
</tr>
<tr>
    <td>Comprehensive Insurance:</td><td><input name="insu" size="5"> per year</td>
</tr>
<tr>
    <td>Road Service Fee:</td><td><input name="rsfee" size="5"> per year</td>
</tr>
<tr>

</tr>
<tr><td colspan="2" bgcolor="#d7d7d7"><center>Variable Costs</center></td></tr>

<tr>
    <td>Petrol:</td><td><input name="petrolwk" size="5"> per week</td>
</tr>
<tr>
    <td>Tyre Replacement:</td><td><input name="tyre" size="5"> per year</td>
</tr>
<tr>
    <td>Speeding fines:</td><td><input name="fines" size="5"> per year</td>
</tr>
<tr>
    <td>Car Service:</td><td><input name="service6m" size="5"> per 6 months</td>
</tr>
<tr>
    <td><input type="button" value="Calculate Total" onClick=cal()>
    <td>$ <input name='answerbox' disabled>
</tr>

</table>
</center>
</form>
</font>
</BODY>
</HTML>
 

dickey

New Member
Messages
128
Reaction score
0
Points
0
it is a regular expression

/ is what is being used instead of quotes
^ means the beginning of the string
[0-9] compares a character if it belongs to the the range 0-9 (checks for numbers)
* means repeat for all characters
\. means until '.' is encountered
? ignores the rest if '.' is not found
+ i forgot what plus does
\s means a single white space
* means check for \s until for all chars remaining
$ means the end of the character

so what this really does is check if your text input contains a valid number with a decimal point and white space until the end of line

return p.test(str) ? parseFloat(str) : 0; -> THis line is a ternary operator or a short form for
if (p.test(str) == true)
{
return parseFloat(str);
}
else
{
return 0; //this is a zero
}

if the string str is a valid decimal number (or float) it will return the number in float format. if not it will return 0.
 

goldy30

New Member
Messages
60
Reaction score
0
Points
0
it is a regular expression

/ is what is being used instead of quotes
^ means the beginning of the string
[0-9] compares a character if it belongs to the the range 0-9 (checks for numbers)
* means repeat for all characters
\. means until '.' is encountered
? ignores the rest if '.' is not found
+ i forgot what plus does
\s means a single white space
* means check for \s until for all chars remaining
$ means the end of the character

so what this really does is check if your text input contains a valid number with a decimal point and white space until the end of line

return p.test(str) ? parseFloat(str) : 0; -> THis line is a ternary operator or a short form for
if (p.test(str) == true)
{
return parseFloat(str);
}
else
{
return 0; //this is a zero
}

if the string str is a valid decimal number (or float) it will return the number in float format. if not it will return 0.

That's well explained. Thanks!
 
Top