I am trying to get the amount of ingredient required for a given portion in the input field.
When the amount changes on the dom, I am unable to acces the initial amount in the html. Because of that, I am unable to get the accurate amount for a give portion in the input field.
function calcAmount() {
let size = document.getElementById('portion').value;
if (size < 1 || size > 5) {
return;
}
let portions = document.querySelectorAll('.span');
for (let i = 0; i < portions.length; i++) {
let amount = parseInt(portions[i].innerText);
let newAmount = amount * size;
let portion = newAmount;
portions[i].innerText = +portion;
portions[i] = '';
}
document.getElementById('portion').value = ' ';
}
<div class="container recipe-portion">
<span>Zutaten für</span>
<div class="portioning">
<input id="portion" type="tex" placeholder="1 bis 5 eingeben" />
<button onclick="calcAmount()" class="btn">Portionen</button>
</div>
</div>
<div class="container recipe-ingredients">
<div class="ingredients">
<p><span class="span">200</span>g Mehl</p>
</div>
<div class="ingredients">
<p><span class="span">200</span>g Zucker</p>
</div>
<div class="ingredients">
<p><span class="span">50</span>g Kakao</p>
</div>
</div>
Use some sort of debugging system to see what is going on when your function runs. You need to visualize your program somehow. Here I used a simple console log command for all variables but there are better ways. And don't get values from html. Keep them in some sort of "source of truth", like an object or something else.