In order to calculate factorial of a given number, user need to enter a number using HTML form. After entering number user presses submit button. On click of submit button JavaScript function is called. The number entered entered by the user is passed to the JavaScript function by using DOM method. The number is then stored in a JavaScript variable. Using for loop the factorial is calculated and finally it is printed on the screen.
Step: Input number from user HTML form
<FORM>
<INPUT type = "number" id = "num">
<INPUT type = "submit" onclick = "fact( )">
</FORM>
Above form allows user to enter a number and submit it using a button. onclick event is used to call the JavaScript function.
Step 2: JavaScript function to calculate factorial
function fact( )
{
var n = document.getElementById("num").value;
var f =1;
for(var i=1; i<=n; i++)
{
f=f*i;
}
document.write(f);
}
Above function is called after user presses submit button. The calculation is made and factorial is printed on the users screen.
<HTML>
<HEAD><TITLE>Factorial</TITLE></HEAD>
<BODY>
<FORM>
<INPUT type = "number" id = "num">
<INPUT type = "submit" onclick = "fact( )">
</FORM>
<SCRIPT>
function fact( )
{
var n. = document.getElementById("num").value;
var f=1;
for(var i = 1; i<=n; i++)
{
f=f*i;
}
document.write(f);
}
</SCRIPT>
</BODY>
</HTML>