I had the following code and I wondered if the question I asked is implementable:
var sum = 0; while (document.getElementById("number").value != 0) { //while the user keeps on entering >0, add to sum sum = sum + document.getElementById("number").value; } document.getElementById("resultpara").value = sum;
<form> <label for="number">Enter a number:</label> <input type="text" name="number" id="number"> <label for="number">Result:</label> <label for="resultpara"></label> <p id="resultpara"></p> </form>
Advertisement
Answer
You will need an input event listener. Also, on form submit, the page will refresh (wiping any variable values to their defaults) unless you stop the propagation of submit event
var sum=0; document.getElementById("number").addEventListener("input", function(event) { var number = Number(event.target.value) || 0; if (event.target.value !== 0) { sum += number; } document.getElementById("resultpara").textContent = sum; event.target.value = null; });
<form> <label for="number">Enter a number:</label> <input type="text" name="number" id="number"> <label for="number">Result:</label> <label for="resultpara"></label> <p id="resultpara"></p> </form>