Hi
I’m new to Javascript and I’m trying to create a calculator that will automatically fill a form field based on the numbers entered into that field multiplied by the price of the product that field represents.
To explain, my editable form fields look like this:
[B]<input name=”123″ type=”text” class=”formField” id=”123″ size=”4″ maxlength=”2″ onChange=”calculate()”>
<input name=”124″ type=”text” class=”formField” id=”124″ size=”4″ maxlength=”2″ onChange=”calculate()”>
I also have some hidden fields that contain the name of each of the form fields I will be displaying and the price that field will cost:
[B]<input type=”hidden” name=”theFields” id=”theFields” value=”123,124″>
<input type=”hidden” name=”thePrices” id=”thePrices” value=”6.50,7.00″>
My Javascript looks like this:
[B]var totalPrice
function calculate()
{
var fields, prices, fieldArray, priceArray
fields = document.form1.theFields.value;
prices = document.form1.thePrices.value;
fieldArray = fields.split(“,”);
priceArray = prices.split(“,”);
var x = 0;
var eachField;
totalPrice = 0;
for (x=0; x<fieldArray.length; x++)
{
eachField = document.form1[fieldArray[x]].value;
if (eachField!=””)
{
totalPrice = totalPrice + ((parseInt(eachField)*(parseFloat(priceArray[x]))));
}
}
totalPrice = totalPrice.toFixed(2);
document.form1.totalPrice.value = “$”+totalPrice;
}
At the moment I’m getting nothing from this, I believe because the line:
[B]eachField = document.form1[fieldArray[x]].value;
isn’t actually working, but I don’t know whether it’s because I can’t use array values in this context or something completely different. Any help would be greatly appreciated.