Trying to get CoinGecko API and user input to calculate and then output

454 Views Asked by At

Ive been trying to make this work for a while but cant seem to get my newbie head around this. I can console.log the coin, but cant seem to get it to multiply with "btcnumber' input and then update .innerText

const api_url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cethereum%2Cbinancecoin%2Ccardano%2Csolana%2Cterra-luna&vs_currencies=usd";
async function getData() {
    const response = await fetch(api_url);
    const data = await response.json();
    console.log(data.bitcoin.usd);
}
getData();


function coinValue() {
    let bitcoin = parseInt(document.getElementById("btcnumber") * (data.bitcoin.usd));
    document.getElementById("c-v").innerText = bitcoin.toFixed(8);
}

document.addEventListener("DOMContentLoaded", function() {
    let submit = document.getElementById("calculateButton");
    calculateButton.addEventListener("click", function() {
        coinValue()
    })

})
<input id="btcnumber" type="number" class="form-control" placeholder="Number Purchased">
                                    
<button id="calculateButton" onclick=coinValue()>Calculate</button>

<h4>CURRENT VALUE <span id="c-v"></span></h4>

1

There are 1 best solutions below

0
On

It happens because in the coinValue() function the data variable does not exists. Make that a global variable by placing it out of the function.

Also inside coinValue() function you have to add .value at the end of your multiplication to get the actual value of the input.

let data;

const api_url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cethereum%2Cbinancecoin%2Ccardano%2Csolana%2Cterra-luna&vs_currencies=usd";
async function getData() {
    const response = await fetch(api_url);
    data = await response.json();
    console.log(data.bitcoin.usd);
}
getData();


function coinValue() {
    let bitcoin = parseInt(document.getElementById("btcnumber").value * (data.bitcoin.usd));
    document.getElementById("c-v").innerText = bitcoin.toFixed(8);
}

document.addEventListener("DOMContentLoaded", function() {
    let submit = document.getElementById("calculateButton");
    calculateButton.addEventListener("click", function() {
        coinValue()
    })

})
<input id="btcnumber" type="number" class="form-control" placeholder="Number Purchased">
                                    
<button id="calculateButton" onclick=coinValue()>Calculate</button>

<h4>CURRENT VALUE <span id="c-v"></span></h4>