/    Sign up×
Community /Pin to ProfileBookmark

Simple Calculator using Form Values and Predetermined Values

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()”>[/B]

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″>[/B]

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;
}[/B]

At the moment I’m getting nothing from this, I believe because the line:
[B]eachField = document.form1[fieldArray[x]].value;[/B]
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.

to post a comment
JavaScript

0Be the first to comment 😎

×

Success!

Help @Brandolph spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.6,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...