I'm trying to learn more about JSON and I'm messing around with the fixer.io API.
I'm creating a script that will convert currencies. I know how to make the request and get the information but I'm having a little trouble making it dynamic. Below is my script that will pull GBP in comparison to USD.
$('#submitButton').on('click', function(e) {
e.preventDefault();
var amount = $('#amount').val();
var convertFrom = $('#convertFrom').text();
var convertTo = $('#convertTo').text();
var requestString = "http://api.fixer.io/latest?base=" + convertFrom;
$.getJSON(requestString, function(result) {
var resultString;
var rate = result.rates.GBP;
resultString = (amount * rate).toFixed(2);
$('#results').html(resultString);
$('#results').removeClass('hide');
});
This is the line that does the magic, obviously:
var rate = result.rates.GBP;
You can change the currency by replacing GBP with any of the supported currencies, such as EUR for example:
var rate = results.rates.EUR;
What I want to do is substitute "GBP" with a variable such as this (which doesn't work):
var currency = "EUR";
var rate = results.rates.currency;
How can I do this with a variable like attempted above? I know there is an answer out there but I don't know what search terms to use to find my answer.
Thank you very much!