Stackers: I coded up a foreign exchange calculator (Indian Rupees to US Dollars) with additions for the Indian counting system of crore and lakh. It works well enough as you see here: [Foreign Exchange Calculator][1] .
In order to improve it, I want to figure a way to have the code go out and grab a JSON object with today's exchange rate which is available via API in many places. While I can write a function that gets the exchange rate, I am having no luck getting an onclick call to make it work.
I looked at the jQuery page but couldn't find an answer to this. If I use the load function, the format is this:
$('selector').load('url',callback) {
do some callback of some kind
};
With a simple page, I can get this to work each time, but -
Because I want to trigger the call for the latest exchange rate with an onclick html call, I want to use a function from the onclick. My first question is, what should my selector be? Normally I would direct it to innerHTML via an id or a class but this doesn't seem to work here.
Secondly, it would seem that I should set my code so that when the page loads, it goes out and notes the current exchange rate. Is there a way for JavaScript/jQuery to do this upon page load even if I haven't called on the function yet? Optimally, I would set the variable to today's rate once and save it locally so I only need to update once a day.
Finally, I have set the function call related to the onclick as:
onclick = run(123.45) with 123.45 being today's rate.
is there a way to replace 123.45 with a function, so a function within a function? I want to use today's rate as returned from the jQuery .load
method as the argument to populate the run function call. No matter how I try, I can't get it to work. I have searched google and haven't found anything which leads me to believe that I am going about this all wrong.
Thanks for any assistance.
// js logic to run calculator with the assumption that each
// calculation involves some pos or negative number and then
// an operator (+-/*) which always yields a positive number.
// ex: 2 + 2 = (4 elements) adding another number and operator
// ex: / 3.5 is now 6 elements in the array.
arr = [];
var total = 0, rupee;
var box = document.getElementById("display");
//jquery call for current Rupee to USD exhcange rate
var url = "https://api.fixer.io/latest?base=USD";
// BELOW IS THE CODE FROM MY FIRST QUESTION
$(**WHATSHOULDTHISSELECTORBE?**).load(url, function(responseTxt) {
var obj = JSON.parse(responseTxt);
rupee = obj.rates.INR;
});
// end of rupee to dollar call
function run(digit) {
x = box.value;
if (x !== '.' && isNaN(x)) {
box.value = "";
}
box.value += digit;
}
function runPlus() {
var digits = box.value;
if (digits === "") {
return;
}
arr.push(Number(digits)); // tried parseInt but dropped decimal nos.
box.value += "+";
arr.push("+");
console.log(arr);
}
function runMinus() {
var digits = box.value;
if (digits === '') {
arr.push("-");
return;
}
arr.push(Number(digits));
box.value = "";
box.value = "-";
arr.push("-");
console.log(arr);
}
function runMult() {
var digits = box.value;
if (digits === "") {
return;
}
arr.push(Number(digits));
box.value = "";
box.value += "*";
arr.push("*");
console.log(arr);
}
function runDiv() {
var digits = box.value;
if (digits === "") {
return;
}
arr.push(Number(digits));
box.value = "";
box.value += "/";
arr.push("/");
console.log(arr);
}
function runEquals() {
var digits = box.value;
if (digits === "") {
return;
}
arr.push(Number(digits));
arr.push("=");
box.value = "";
total = arr[0];
var ans = calculateArr(arr);
box.value = ans;
}
function runClear() {
box.value = "";
arr = [];
}
function calculateArr(arr) {
for (var i = 0; i < arr.length; i = i + 2) {
if (arr[i + 1] === "+") {
total = total + arr[i + 2];
} else if (arr[i + 1] === "-") {
total = total - arr[i + 2];
} else if (arr[i + 1] === "*") {
total = total * arr[i + 2];
} else if (arr[i + 1] === "/") {
total = total / arr[i + 2];
} else if (arr[i + 1] === "=") {
total = total;
} else alert("Error");
}
return ReplaceNumberWithCommas(total);
}
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n = yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
if (n[1]) {
n[1] = n[1].split("").slice(0, 2);
n[1] = n[1].join("");
}
return n.join(".");
}
[1]: http://codepen.io/Qstreet/pen/GovZdg
Since you need to retrieve values automatically on page load , you need to use xhr request.
$.get( "your-url", function( data ) {
$( "where you want to insert it" ).html( data );
//or call your-custom-function(data);
});
If you want to fetch values upon click event , insert above code as a function to jquery click event handler
Thanks so much @Anmol. I got it working with this:
var url = "http://api.fixer.io/latest?base=USD";
function runRup() {
var xhr = new XMLHttpRequest();
xhr.open("GET",url,false);
xhr.send(null);
var rt = JSON.parse(xhr.responseText);
return rt.rates.INR;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.