PDA

View Full Version : Adding Problem


Jack5000
07-28-2005, 06:40 PM
All I want to do is add two numbers together and have them appear in the field after the "Total" button.
But the two numbers are simply appearing side by side :confused:
I bet this is pretty simple but I'm clueless so...

Here's the code:

<SCRIPT LANGUAGE="JavaScript">

function calc1(form)
{form.surcharge.value = form.a.value * form.b.value * .010}

function calc2(form)
{form.total.value=form.surcharge.value + form.a.value}

// End -->

</script>

<form method=post action="/cgi-bin/seattle/personalshipmentinvoice.cfm" method="post">

<div align="center"><h1>Personal Shipment Invoice</h1></div>

<hr>

Name of Sender: <input type="value" NAME="name">
<br>

<br>
Name of Recipient: <input type="text" NAME="name">
<br>

<br>
<p>


Type of shipment: <input type="radio" NAME="UPS" VALUE="UPS"> UPS <input type="radio" NAME="Priority"

VALUE="Priority">Priority Mail

<br>
<br>


<h2>UPS Ground and Air Shipments</h2>

<h3>Air fuel charge = 9.5% &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ground fuel Charge = 2.5%</h3>

Shipping Charge: <input type="value" name="a" size=5><br><br>

<font color="#FF0000">Fuel Surcharge:</font>

<input type="value" name="b" size=5> %

<br><br>

<input type="button" value="Calculate" onClick="calc1(this.form)">
<br>
Surcharge Amount: <input type="value" name="surcharge" size=5 maxlength=40><br>

<br>
<br>

<input type="button" value="Total" onClick="calc2(this.form)"> = <input type="value" name="total" size=5>
<br>

</form>

SpirtOfGrandeur
07-28-2005, 07:11 PM
input.value = string

You need to parseInt() (http://www.google.com/search?hl=en&q=javascript+parseInt&btnG=Google+Search) to be able to create numbers out of it.

Philip M
07-28-2005, 07:18 PM
In JavaScript values are strings by default, and here the + sign is not addition but concatenation. So 100+10 comes out as 10010, not 110.

If you change the script to

function calc1(form){

form.total.value = (form.a.value * .10)}

function calc2(form)

{form.x.value=(form.total.value*1) + (form.a.value*1)}

// End -->

You will find it works.

The simplest way to change a string to a number is to multiply it by 1.

Another way is to use parseInt or parseFloat which will return an integer or a floating point number respectively.

Note that your code contains no checks that the user enters valid data,
that is numbers or sensible numbers.

You have also misinterpreted input type=value. This HTML control specifies a default value to appear in the box, for example input type="text" value="A default value here".

You should change all your input type=value to read input type=text.

Kor
07-29-2005, 10:49 AM
The simplest way to change a string to a number is to multiply it by 1.

as simple as Number(string) method. :)