The value will flash only once in the html textbox.

while loop in javascript

        

function calc(){
var one = document.getElementById("fv").value;
var two = document.getElementById("sv").value;
var one1 = parseInt(one); 
var two1 = parseInt(two);
var total = 0;
if(one1<=two1){
while (one1 <= two1){
total = total+one1;
one1++;                         
total=total;
}
document.getElementById("tv").value = total;
}}
calc() //call function
</script>
<form>

      

There is some confusion about using while loop in java script. can i use a while loop for this type of computation?

<p>"Calculation of sum between two numbers"</p>
<h5>First Number</h5><input type ="text" value="1" name="firstv" id="fv"><br>
<h5>Second Number</h5><input type="text" value="100" name="sectv" id="sv"><br>
<h5>Value</h5><input type="number" value= "" name="tv" id="tv"><br>
<button onclick="calc()" value="click">Calculate</button><br>
</form>
</body>
</html>

      

+3


source to share


1 answer


You need to stop the button from submitting the form. If you make sure your Javascript function appears in front of your html and your button looks like this:

<button onclick="calc(); return false;" value="click">Calculate</button>

      

Then it should work fine



If you need to call the first calc () before the button is clicked, you need to do so when the document is ready:

document.addEventListener("DOMContentLoaded", function(event) { 
   calc();
});

      

Example

+3


source







All Articles