HTML/Javascript Currency converter

I’m trying to make a currency converter that converts between several different currencies on change. It uses some pre-determined exchange rates. Input boxes display, but none of the javascript seems to work. Any help?

Edited with updated code. Still does not convert anything.

HTML body:

<body onload="init()">

    <input type="text" id="GBP" size="10" value="0" onchange="gbp()"/>
    <label for="GBP"> GBP </label>

    </br>

    <input type="text" id="USD" size="10" value="0" onchange="usd()" />
    <label for="USD"> USD </label>

    </br>

    <input type="text" id="EUR" size="10" value="0" onchange="eur()" />
    <label for="EUR"> EUR </label>

    </br>

    <input type="text" id="CAD" size="10" value="0" onchange="cad()" />
    <label for="CAD"> CAD </label>

    </br>

    <input type="text" id="AUD" size="10" value="0" onchange="aud()" />
    <label for="AUD"> AUD </label>



</body>

Javascript code:

var gbp, usd, eur, cad, aud;
function init()
{
    gbp = document.getElementById("GBP");
    usd = document.getElementById("USD");
    eur = document.getElementById("EUR");
    cad = document.getElementById("CAD");
    aud = document.getElementById("AUD");
}

function gbp()
{
    usd.value = parseFloat(gbp.value) * 0.49246;
    eur.value = parseFloat(gbp.value) * 0.69714;
    cad.value = parseFloat(gbp.value) * 0.50221;
    aud.value = parseFloat(gbp.value) * 0.43497;
}

function eur()
{
    gbp.value = parseFloat(eur.value) * 1.43448;
    usd.value = parseFloat(eur.value) * 0.70641;
    cad.value = parseFloat(eur.value) * 0.72037;
    aud.value = parseFloat(eur.value) * 0.62382;
}

function cad()
{
    gbp.value = parseFloat(cad.value) * 1.99169;
    usd.value = parseFloat(cad.value) * 0.98054;
    eur.value = parseFloat(cad.value) * 1.38814;
    aud.value = parseFloat(cad.value) * 0.86613;
}

function aud()
{
    gbp.value = parseFloat(aud.value) * 2.29964;
    usd.value = parseFloat(aud.value) * 1.13262;
    eur.value = parseFloat(aud.value) * 1.60329;
    cad.value = parseFloat(aud.value) * 0.88297;    
}

function usd()
{
    gbp.value = parseFloat(usd.value) * 2.03032;
    eur.value = parseFloat(usd.value) * 1.41544;
    cad.value = parseFloat(usd.value) * 1.01941;
    aud.value = parseFloat(usd.value) * 0.88297;
}

Answer

You need to remove var statements from initialize function and add them above this function:

var gbp, usd, eur, cad, aud;
function init()
{

    gbp = document.getElementById("GBP");
    usd = document.getElementById("USD");
    eur = document.getElementById("EUR");
    cad = document.getElementById("CAD");
    aud = document.getElementById("AUD");
    //...

In this case variables gbp, usd, eur, cad, aud will be visible in other functions scopes.

Probably you need to read more about variables and scopes. For example at MDN. Scopes and closures are very important in JS.

Leave a Reply

Your email address will not be published. Required fields are marked *