I tried to make an input and whatever the number is there, to add it using a button. I cannot understand what my code miss and why is not adding the value from the input.
Do I need to convert to a number from a string or?
let funds = document.getElementById("funds");
let input = document.getElementById("input").value;
let add = document.getElementById("add");
let base = 0;
function adauga() {
funds.innerText = base += input;
}
<p>Funds Available</p>
<p id="funds">0$</p>
<input id="input" type="number" class="text-black w-28 rounded-xl border-2 border-red-700" />
<button id="add" onclick="adauga()" class="ml-4 bg-red-700 px-3 py-1 rounded-xl">Add</button>
Instead of
let input = document.getElementById("input").value;
You should be using
let input = document.getElementById("input");
and get the current input value with
funds.innerText = (base+= input.valueAsNumber)+"$";
Two issues.
The first is, as you correctly pointed out, that the number needs to be coerced to a string.
The second is that you're immediately setting the value of input to that element's value rather than using the new value of the input box to change the text content. So pick up the value in the function instead.
let funds = document.getElementById("funds");
let input = document.getElementById("input");
let add = document.getElementById("add");
let base = 0;
function adauga() {
funds.textContent = `${(base += Number(input.value))}$`;
}
<p>Funds Available</p>
<p id="funds">0$</p>
<input id="input" type="number" class="text-black w-28 rounded-xl border-2 border-red-700" />
<button id="add" onclick="adauga()" class="ml-4 bg-red-700 px-3 py-1 rounded-xl">Add</button>
Additional documentation