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 are some confusion using while loop in java script. can i use while loop for those type of calculation?
<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>
You need to stop the button from actually submitting the form. If you make sure that your Javascript function appears before your html and your button looks like this:
<button onclick="calc(); return false;" value="click">Calculate</button>
Then it should work properly
If you need to call the first calc() before the button is clicked, you need to do it when the document is ready:
document.addEventListener("DOMContentLoaded", function(event) {
calc();
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments