: If Number value is 21 or higher then the amount returned is Number
: value * 120 (£) * 10 (%) to give a discount on 21 and higher.
input_number = eval(form.Number.value);
input_price_pounds = 120.00;
input_price_pennies = input_price_pounds * 100;
TotalPayPennies = Math.round( (input_number * input_price_pennies *
(input_number <= 20 ? 1: 0.9 ) ) );
form.Amt0.value = AddDecimal(TotalPayPennies);
Here the 0.9 stands for 10% discound and 1 for normal price.
And 20 of cause stands for the max. # of items where you get no discount.
I hope this helps.
I doubt it will:
1) All the variables above are global (Bad Idea [TM]),
2) You use eval() for no particular reason,
3) input_price_pounds is useless. It would make more sense to simply use a
literal in its place and add a comment next to input_price_pennies (this
is obviously a minor point), and
4) You don't validate that the value is in fact a number and branch if
it's not.
To the OP: it would be nice to know where this magic £120 comes from. It's
much easier to write a function when one knows exactly what it's supposed
to do and why (have the 'do', but not the 'why').
A typical discount function might look like:
function applyDiscount( number, level, discount ) {
if( number > level ) {
return number * ( 1 - discount / 100 );
}
return number;
}
This could be called like so:
// price (in pounds) has already been
// declared and contains a number (not a String)
price = applyDiscount( price, 20, 10 );
Here, if 'price' is greater than £20, a 10% discount is applied
(multiplied by 0.9). However, your 'magic' £120 confuses the issue here.
In the meantime, to get a (valid) value from a control, you could use this:
function getValue( control ) {
return Number( control.value );
}
If the form control contains a valid number, that number is returned. If
it contains text (or some other erroneous value), it will return NaN. To
test for the latter, use the isNaN() function.
This could be called like so:
var price = getValue(document.forms['your_form'].elements['cost']);
if( isNaN( price )) {
// The 'cost' field in the 'your_form' form contained text
// (is not a number)
} else {
// The 'cost' field contained a valid number
}
If you can clear up the £120 business, I might be able to provide a full
solution.
One last point, when you access form controls, it's better to use what I
call, for lack of a better name, the 'Collection syntax'. It should work
across every browser - document.form_name.control_name certainly does not.
The previous example would look like:
document.forms['form_name'].elements['control_name']
Mike