Im quite new at Javascript however I have been trying to create a currency converter using html select which is working great, however when calling the function it seems to skip straight over the if statements straight onto the else { } statement
function convUSD()
{
RATE_GBP = 0.632111252;
RATE_EURO = 0.746435769;
RATE_AUD = 0.92945441;
if(document.selectBox.slBoxCurrency.selectedIndex == 0 && document.frmCurrencyC.radioUSD.checked)
{
window.alert("Sorry cant do USD to USD convertion! Please select another value.");
}
else if(document.selectBox.slBoxCurrency.selectedIndex == 0 && document.frmCurrencyC.radioGBP.checked)
{
inputBox = parseFloat(document.frmCurrencyC.textInputNum.value);
outPutBox = inputBox * RATE_GBP;
document.frmCurrencyC.textOutPutTotal.value = outPutBox;
}
else if(document.selectBox.slBoxCurrency.selectedIndex == 0 && document.frmCurrencyC.radioEURO.checked)
{
inputBox = parseFloat(document.frmCurrencyC.textInputNum.value);
outPutBox = inputBox * RATE_EURO;
document.frmCurrencyC.textOutPutTotal.value = outPutBox;
}
else if(document.selectBox.slBoxCurrency.selectedIndex == 0 && document.frmCurrencyC.radioAUD.checked)
{
inputBox = parseFloat(document.frmCurrencyC.textInputNum.value);
outPutBox = inputBox * RATE_AUD;
document.frmCurrencyC.textOutPutTotal.value = outPutBox;
}
else
{
window.alert("Whoops there was an error");
}
}
The first If statement works fine however when I actually want to do for example USD to GBP it heads straight to the else statement.
If you guys spot any errors or just well anything it would be much appreciated.
You’ve got your logic mixed up:
First you check to see which currency you are converting to by looking at which radio was selected:
Then I would expect you would look at the drop down list to see what currency you are converting from, but instead, you check the radios, enforcing that the drop down list selection matches the “to” currency:
Looking at your code, it seems that in your first function, you need to be checking for the “from” currency, not the “to” currency. So, in
calculateCC(), look at the drop down list, instead of the radio buttons:Working demo: http://jsfiddle.net/X8MyF/2/