JBoom JBoom - 1 year ago 44
Javascript Question

JavaScript function will only work once

I have a JavaScript function that is triggered onchange. What it does is take the value from a input field and then add it to the value entered in another field and then display the answer in a different field.

It works fine the first time, but when I enter a new value and leave the field there is an error:

TotalPurchasePrice is not a function


function TotalPurchasePrice(BuyinPrice, TopupAmount) {
var BuyinPrice
var TopupAmount
BuyinPrice = BuyinPrice.toString().replace(/\£|\,/g, '');
TopupAmount = TopupAmount.toString().replace(/\£|\,/g, '');

TotalPurchasePrice = (BuyinPrice * 1) + (TopupAmount * 1);

document.getElementById('tTotalPurchasePrice').value = TotalPurchasePrice;
}


Can anyone tell me why this would only work once?

Answer Source

This line :

TotalPurchasePrice = (BuyinPrice * 1) + (TopupAmount * 1);

replaces the TotalPurchasePrice function by a number. Then it's not a function, hence the error you have.

Use a different variable name :

var totalPrice = (BuyinPrice * 1) + (TopupAmount * 1);
document.getElementById('tTotalPurchasePrice').value = totalPrice;

You could also simply have added the var keyword but it would have made the code confusing.

A way to reduce the probability of such errors is to follow best practices when naming functions and variables. Here you should have named your function as a verb to denote an action instead of a value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download