0

Hello fellow Stackers!

I am trying to convert US Dollars to South Africa Rands on a web page.

I have a Javascript function attained from here.

The function works fine, but I can't seem to return a value for me to use :/

function getRate(from, to) {
  var script = document.createElement('script');
  script.setAttribute('src', "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+from+to+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=parseExchangeRate");
  document.body.appendChild(script);
}

function parseExchangeRate(data) {
  var name = data.query.results.row.name;
  var rate = parseFloat(data.query.results.row.rate, 10);
  console.log('rate: ' + rate);
  return rate;
}

var dollarRand = getRate("USD", "ZAR");

var priceConvert = document.getElementsByClassName('price-convert');
var currentPrice = priceConvert[0].innerHTML;
currentPrice = currentPrice * dollarRand;

Thank you in advance for your assistance!

Aaron Matthews
  • 128
  • 3
  • 13
  • What exactly do you mean by 'I can't seem to return a value for me to use' ? – Danmoreng Jul 07 '17 at 10:00
  • 1
    The callback function gets called automatically, when the external script is done loading. It is not you calling that function, but the script itself. So you can not really return something from there for you to use elsewhere. Whatever you need to do with this data - do it _inside_ the callback function. – CBroe Jul 07 '17 at 10:00
  • @Danmoreng when I try use the value of the exchange rate (variable *dollarRad*) it gives me undefined. – Aaron Matthews Jul 07 '17 at 10:03
  • @CBroe thank you! I will try that :) – Aaron Matthews Jul 07 '17 at 10:04

0 Answers0