I'm trying to multiply two numbers that I've got from 2 inputs within 2 functions. How can I access the value outside the function? Is this the correct way of doing it? At this point, I get NaN at total.
let coinName = document.getElementById("coinName");
let nrCoins = document.getElementById("nrCoins");
let inputName = document.getElementById("inputName");
let inputNr = document.getElementById("inputNr");
let inputValue = document.getElementById("inputValue");
let coinValue = document.getElementById("coinValue");
let total = document.getElementById("total");
function coinNamer() {
coinName.innerHTML = inputName.value;
inputName.value = "";
}
function nrCoinss() {
nrCoins.innerHTML = inputNr.valueAsNumber;
inputNr.value = "";
}
function coinValuee() {
coinValue.innerHTML = inputValue.valueAsNumber + "$";
inputValue.value = "";
}
total.innerHTML = nrCoins * coinValue;
The problem is that both nrCoins
and coinValue
are HTMLElement
. They are not numbers. That's why the NaN
.
To solve this, do this-
total.innerHTML = nrCoins.innerHTML * coinValue.innerHTML;
But there is still a problem. Because coinValue.innerHTML
contains the "$" sign at the end. We need to remove it and multiply it.
So the correct solution will be-
total.innerHTML = nrCoins.innerHTML * coinValue.innerHTML.slice(0, coinValue.innerHTML.length - 1);
On a separate note- The multiplication of two strings work as long as they are valid representations of numbers.
console.log("12" * "12")
console.log(" 12 " * " 12")
console.log("12\n\r" * "12")
you have to convert input value to number
and return it.
this is a example explain to you how to use your input and calculate total
const inputPrice = document.getElementById('price'),
inputQte = document.getElementById('qte'),
SubmitButton = document.getElementById('btn')
let total = 0
SubmitButton.addEventListener('click', function (e) {
// e.preventDefault() for do not refresh the page
e.preventDefault()
// convert and assign price * qte to total
// the + operator is to convert from string to number
total = +inputPrice.value * +inputQte.value
console.log(total)
})
nrCoins and coinValue both refers to DOM elements and you can not multiply them . Instead return your inputNr.value and inputValue.value from their respective functions and use those functions to multiply these numbers i.e
function nrCoinss() {
nrCoins.innerHTML = inputNr.valueAsNumber;
inputNr.value = "";
return inputNr.valueAsNumber;
}
function coinValuee() {
coinValue.innerHTML = inputValue.valueAsNumber + "$";
inputValue.value = "";
return inputValue.valueAsNumber;
}
total.innerHTML = nrCoinss() * coinValuee();