Forum Moderators: open

Message Too Old, No Replies

Calculating from an Array

Modifying or adding to existing code to add tax 'on the spot'

         

mangotude

10:08 am on Oct 25, 2005 (gmt 0)

10+ Year Member



A while back I got some help with sorting out my problem of having three different products with different service options. They were put into an array:

This is at the form application – fairly standard form, with the customer putting their address details, and then choosing the product and service options – and having the price displayed on the same screen.

The basic javascript code used to calculate the price is:

In the head:


<script type="text/javascript" language="javascript">
function setSelect() {
// set local variables to reference form elements
coun=document.getElementById("product");
serv=document.getElementById("service");
fPRICE=document.getElementById("fPRICE");

// get the numbers to add up the PRICE
product=Number(coun.value);
service=Number(serv.value);

// check what was selected, and set the PRICE variable
PRICE = product + service + ".00";

// update the fPRICE form element with the final PRICE value
fPRICE.value=PRICE;
fPRICE.text=PRICE;

}

For the form details


<select id="product" onchange="void(setSelect())" name="product" size="3">
<option value=1 selected />STANDARD
<option value=6 />DELUXE
<option value=7 />PRESTIGE
</select>

<select id="service" onchange="void(setSelect())" name="service" size="3">
<option value="24" selected>Standard Service</option>
<option value="39">Swift Service</option>
<option value="59">Express Service</option>
</select>

and the price is displayed with


<td class="main_text">
<p><b><font color="#FF0000">Price in GBP (&pound;)
<input type="text" name="price" id="fPRICE" size="6" Readonly>
</font></b></p>
</td>

The above has worked, and continues to work perfectly fine.

For the customers address details, I have a standard list of countries – it lists all countries, but the few lines below should be enough to show the setup.


<select name="customercountry">
<option value=""selected>Please Select</option>
<option value="">------------------------</option>
<option value="United Kingdom">United Kingdom</option>
<option value="Australia">Australia</option>
[/select]

What I’m looking to do is for to be able to ‘add in’ VAT if a customer chooses United Kingdom (or other EU countries, France, Germany, Spain etc), so that the price displayed on screen includes that amount.

I’ve found this piece of code on various sites, so it seems a good place to start - in case I cut the wrong part, I’m going to include in its entirety.


#put this bit between the head tags

<SCRIPT LANGUAGE="JavaScript">

<!-- Begin
function doMath() {
var one = eval(document.myform.total.value)
var two = eval(document.myform.vat.value)
var prod = one * two
document.myform.amount.value=custRound(prod,2);
}

function custRound(x,places) {
return (Math.round(x*Math.pow(10,places)))/Math.pow(10,places)
}

// End -->
</SCRIPT>

#this should be placed in the body of the page.
#you can add other fields to the form and use it with a formmail or other script.

<CENTER>
<FORM NAME="myform">
<table border="1">
<tr>
<td>Total excluding VAT</td>
<td>
<input type="text" name="total">
</td>
</tr>
<tr>
<td>VAT status</td>
<td>
<select name="vat">
<option value="1.175" selected>In Europe (with VAT)</option>
<option value="1.00">Outside Europe (no VAT)</option>
</select>
</td>
</tr>
<tr>
<td>Total including VAT</td>
<td>
<input type="text" name="amount">
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="button" value="Calculate" onClick="doMath()" name="button">
</td>
</tr>
</table>
</FORM>
</CENTER>

What I’m wondering is, will this code be something I can adjust to my needs? I don’t want to change the value in my customercountry from “united Kingdom” to “1.175” unless I absolutely have to, as it would screw up a lot delivery procedures.

What I was thinking (and hoping) is this:

During the SetSelect function to calculate current price – could some sort of IF statement be used


I know this isn’t javascript, more a sort of logic outline, if there’s such a thing]

IF customercountry=”United Kingdom” THEN fPRICE=fPRICE*1.175 [or run doMath function or a variant of it]
ELSE ..just run SetSelect as normal.

So if anyone has made it to tbe bottom, I’m wondering if any of this is possible, is it a good idea to implement this way, and any ideas of how it should look code wise. Any advice etc greatly appreciated.

James

PS _ had a problem with the formatting - all the code should be the same size.

mangotude

4:51 pm on Oct 26, 2005 (gmt 0)

10+ Year Member



Would it be possible incorporate the VAT function within the existing setSelect function, or should I call a different routine within it?

Is it as simple (I can't believe I'm saying that about Javascript) as running a conditional statement within setSelect to run an additional calculation?

mangotude

8:25 pm on Oct 31, 2005 (gmt 0)

10+ Year Member



I'm still unsure as to the best way of doing this:

What I was thinking was is:

Get the value of customercountry


cust=document.getElementById("customercountry")

And adapt

PRICE = country + service + ".00";

into some type of an if else statement.


if (customercountry=="United Kingdom")
{
PRICE = (country + service + ".00")*1.175;
}
else
if (customercountry=="Ireland")
{
PRICE = (country + service + ".00")*1.175;
}
else
PRICE = country + service + ".00";

Any help appreciated. If no solutions are forthcoming, then pointing out of seemingly obvious errors would also help greatly.

Bernard Marx

11:08 pm on Oct 31, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just taking a look at your most recent post, there is a little confusion as to the variables (and what they represent)

cust=document.getElementById("customercountry")

OK, then

if (customercountry=="United Kingdom")..

Where does the var and value,

customercountry
, come from?
and

PRICE = (country + service + ".00")*1.175; 

the same for the var,

country
.

-------------------------------------------------
/* Not much point, and risky if previous sum is not integral */

PRICE = (country + service [red]+ ".00"[/red])*1.175;

There's an error here. Presumeably the sum, country + service, is an integer, to which we add ".00" to get a nice currency string. Hmmm, then it's multiplied by the VAT. The implicit number conversion is OK, but we've lost the trailing ".00", because the result is a number.

What format do you want the number to be in?

-------------------------------------------------
From the initial post:

// set local variables to reference form elements 
coun=document.getElementById("product");
serv=document.getElementById("service");
fPRICE=document.getElementById("fPRICE");

1) These are not local variables. You need to prefix the declaration of each with

[blue]var[/blue]
to do that:

[blue]var[/blue] coun=document.getElementById("product");

2) IE (and other browsers to) conveniently turns all ids into global variables that reference the respective elements. This means that this statement in a function, without using

var
, is likely to cause some grief in IE (although I'm not 100% sure why).

fPRICE=document.getElementById("fPRICE");

Bernard Marx

11:17 pm on Oct 31, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How about this to replace the IF..ELSE block?:


/* change corrupted [b][red]¦¦[/red][/b] chars for pipes */
var VAT =
{
"United Kingdom": 1.175,
"Ireland" : 1.175,
"Sweden" : 1.5
}
[customercountry][red]¦¦[/red]1;

Now you have the correct VAT for the country, or 1 if the country isn't listed.
You can safely do the calculation.

mangotude

1:24 pm on Nov 1, 2005 (gmt 0)

10+ Year Member



Hi Bernard,

Thanks for the message. there's more than a little confusion, and not only with the variables :)

Having VAT set up as a separate 'block' seems far more simple, but im still not entirely sure how to implement - i'll try to implement it first and then come back with the next mess.

thanks again.

mangotude

2:15 pm on Nov 1, 2005 (gmt 0)

10+ Year Member



OK

The owner edit on the above has expired. I'm going to try to break it down and focus only on the 'new' code initially.

To add to this, I would need


var cust=document.getElementById("customercountry");

What would I need to get the value from customercountry?
I know this is wrong as its text, but I'll put it in so i can be corrected.
[code]
cust=Number(coun.value);

and then I would 'drop' in the VAT piece of code, but not entirely sure where.

for the final number presentation, I would like it to be

00.00 presentation

Bernard Marx

3:58 pm on Nov 1, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What would I need to get the value from customercountry?

Here's the opener for the select tag (from post #1)

<select name="customercountry"> 

You can't use

getElementById
. It doesn't have an
id
. It's a
name
.
(here's one way)

var countrySel = document.getElementsByName("customercountry")[0];

-

getElementsByName
always returns a collection, even if there's only one elm.

Now get value (a switch to old-style code, for convenience)..

var country = countrySel.options[countrySel.selectedIndex].value;

for the final number presentation, I would like it to be 00.00 presentation

Does that mean that you want the figure rounded to the nearest dollar (pound, krona), or just to be in 2dp?

If you want rounded, use

Math.round

For formatting look up the string method:
toFixed

mangotude

9:45 pm on Nov 1, 2005 (gmt 0)

10+ Year Member



Thanks again. I'm away most of tomorrow, so I'll let you know how things are in a couple of days. appreciate the ongoing feedback.

mangotude

10:51 pm on Nov 1, 2005 (gmt 0)

10+ Year Member



I thought i'd fiddle for a half hour, not expecting much....and I've got the basic setup working great. So many thanks.

Completely beaten by how to implement the toFixed function, but I'll come back to it later.

Bernard Marx

11:21 pm on Nov 1, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sorry, my fault. It's a number method (returning string):


alert((123).toFixed(2) ) // => "123.00"
// rounds automatically
alert( (123.4567).toFixed(2) ) // => "123.46"

mangotude

4:14 pm on Nov 4, 2005 (gmt 0)

10+ Year Member



the code i added/changed ended up as:


var coun=document.getElementById("country");
var serv=document.getElementById("service");
var fPRICE=document.getElementById("fPRICE");
var countrySel = document.getElementsByName("customercountry")[0];

var country=Number(coun.value);
var service=Number(serv.value);
var customercountry=countrySel.options[countrySel.selectedIndex].value;

if (customercountry=="United Kingdom")
{
PRICE = (country + service)*1.175;

}
else
if (customercountry=="Ireland")
{
PRICE = (country + service)*1.6;
}
else
PRICE = country + service + ".00";

fPRICE.value=PRICE;
fPRICE.text=PRICE;

numbers used aren't necessary correct, just to show its working ok.

The only thing I'm unsure of is where to place the ToFixed(2) code - I've tried it in different places, but it's only negated the function or had no effect at all. Any advice appreciated.

mangotude

11:06 pm on Nov 9, 2005 (gmt 0)

10+ Year Member



I've been fiddling with toFixed, trying to get it working...still no joy. Should it be used in initial definitions, every time it calculates the price, or at the final output stage?

Bernard Marx

1:40 am on Nov 10, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



change corrupted ¦¦ chars to pipes


/* Add toFixed method, if not supported */
if(!Number.prototype.toFixed)
Number.prototype.toFixed = function(d){
return ~~this+'.'+String(Math.round((this*1[b][red]¦¦[/red][/b]1)*100)).slice(-d);
}

var PRICE;
var country = Number(document.getElementById("country").value);
var service = Number(serv.document.getElementById("service").value);
var countrySel = document.getElementsByName("customercountry")[0];
var customercountry = countrySel.options[countrySel.selectedIndex].value;
var fPRICE = document.getElementById("fPRICE");

if (customercountry=="United Kingdom")
PRICE = (country + service)*1.175;
else if (customercountry=="Ireland")
PRICE = (country + service)*1.6;
else
PRICE = country + service; // don't add string here

PRICE = PRICE.toFixed(2)

fPRICE.value = PRICE;
fPRICE.text = PRICE;

mangotude

9:13 pm on Nov 11, 2005 (gmt 0)

10+ Year Member



that's got it working.

many, many, many thanks - have been dreading having to change this code.