user1085773
user1085773

Reputation: 21

trouble with a currency converter in javascript

Im having trouble with this javascript. here is a n example

 window.onload = initPage;

var euro;
var convert;

function initPage()
{
    document.getElementById("convertButton").onclick = calcAnswer();
    document.getElementById("conversionType").onchange = calcAnswer();
}

function calcAnswer()
{
    //alert(document.getElementById("conversionType").value);

    var value1 = document.getElementById("amount").value;
    var conversionType = document.getElementById("conversionType").value;
    //alert(conversionType);

    if(var value = document.getElementById("conversionType").value=="polish");
        document.getElementById("answer").value=(value1-32)/9*5;
    else
        document.getElementById("answer").value=value1*9/5+32;
}

here is the html

  <h1>Currency Converter</h1>


  <form name="convert">

Choose which currency you would like to convert to the Euro:
<select id="conversionType">
    <option value="polish">Polish Zloty</option>
    <option value="ukraine">Ukraine Hryvnia</option>
</select>
</br>
</br>

<hr>
      Amount:<input id="amount" type="text" />
<input id="convertButton" type="button" value="Convert->"/>
      To:
<input id="answer" type="text" name="answer" readonly="readonly"/>


</form>

im using an old temperature converter and havent changed that part part but even that part is not working.

Upvotes: 0

Views: 1039

Answers (2)

jfriend00
jfriend00

Reputation: 707248

For starters, these two lines are wrong:

document.getElementById("convertButton").onclick = calcAnswer();
document.getElementById("conversionType").onchange = calcAnswer();

Change them to:

document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;

You want to assign a function reference to onclick and onchange, not actually call the function and assign the return value.

Then, fix the if statement in calcAnswer like this:

function calcAnswer()
{
    var amount = document.getElementById("amount").value;
    var conversionType = document.getElementById("conversionType").value;
    var answerElement = document.getElementById("answer");
    //alert(conversionType);

    if(conversionType == "polish") {
        answerElement.value = (amount-32)/9*5;
    } else {
        answerElement.value = amount*9/5+32;
    }
}

Upvotes: 3

Tuan
Tuan

Reputation: 5412

Should be

document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;

(without the parens)

You just need to reference the function, not execute it.

Upvotes: 0

Related Questions