I have separated my form in different functions and although each one works, I can't find a way to use the value returned in the total function.
function adult() {
let a = document.getElementById("adulte").value;
let t = a * 100
document.getElementById("asub").innerHTML = t
//document.getElementById("sub-a").value = t;
console.log(t);
document.getElementById("tprice").innerHTML = a;
return t;
}
function total() {
let a = adult();
document.getElementById("tprice").innerHTML = a;
console.log(a);
}
<input id="adulte" name="adulte" style="width: 40px" onchange="adult();" />
<span id="aprice"> 100</span>$/nuit
<p> Hébergements pour les adultes = <span id="asub">100</span>$</p>
<button id="total" name="total" onclick="total();">calculate</button>
<span id="tprice"> 50</span>$
I think the following code should work, but I recommend to use form tag..
You don't want trigger adult() every time on input change, which I feel is unnecessary and redundant. still there is a lot of room for code optimization, but I don't want to spoil your method of doing things.
Also in html5, onchange event triggered on two conditions :
1.on Enter Key Press
2.on loosing focus (on blur)
<html>
<head>
<script>
function adult(input) {
let a = input;
document.getElementById('asub').innerHTML = a * 100;
document.getElementById('tprice').innerHTML = a;
return t;
}
function total(event) {
let a = adult(event.target.value);
document.getElementById('tprice').innerHTML = a;
}
</script>
</head>
<body>
<input type="number" id="adulte" name="adulte" style="width: 40px" onchange="total(event)" min=0 />
<span id="aprice"> 100</span>$/unit
<p>Hébergements pour les adultes = <span id="asub">100</span>$</p>
<button id="total" name="total" onclick="total();">calculate</button>
<span id="tprice"></span>
</body>
</html>
Added Stackblitz code: click here