Reputation: 21
How do I combine these two functions and alert var price
in the updatePrice
function? Currently I am only able to alert price
inside the first function but I would like to call alert(price)
inside updatePrice
function.
$(document).ready(function()
{
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': 'https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD',
'dataType': "json",
'success': function (data) {
json = data[0].price_usd;
var price = JSON.stringify(json);
var price = JSON.parse(price);
alert(price);
}
});
})();
function updatePrice ()
{
var ethprice = parseFloat($(".usd-input").val());
var ethtotal = (ethprice) / 298;
var ethtotal = ethtotal.toFixed(3);
if(isNaN(ethtotal)) {
var ethtotal = "";
}
$(".eth-input").val(ethtotal);
var tvcprice = parseFloat($(".usd-input").val());
var tvctotal = (tvcprice) / 1;
var tvctotal = tvctotal.toFixed(3);
if(isNaN(tvctotal)) {
var tvctotal = "";
}
$(".tvc-input").val(tvctotal);
}
$(document).on("change, keyup", ".usd-input", updatePrice);
})
Upvotes: 0
Views: 59
Reputation: 24174
Declare the first function (say, showAlert()
) as a global function then call it from updatePrice() function.
And also declare price
variable in global scope since you want to access it from updateFunction()
function.
var price; // declare in global scope, so can be accessable from anywhere.
var showAlert = function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': 'https://api.coinmarketcap.com/v1/ticker/ethereum/?
convert=USD',
'dataType': "json",
'success': function (data) {
json = data[0].price_usd;
price = JSON.stringify(json);
price = JSON.parse(price);
alert(price);
}
});
}
showAlert();
Now, just call showAlert() from inside updatePrice() function.
Upvotes: 2