In this example I will show you how to find the number of values in a given range divisible by a given value.
Solution 1(Given Numbers):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <script> let numFrom=10,numTo=100,numDivider=5; for(let i=numFrom;i<=numTo;i++) { // if iteration number divisible to numDivider, block works. if(i%numDivider==0) { document.write(`${i} is divisble to ${numDivider}<br>`); } } </script> |
Output:
Solution 2(Entered by User): Firstly I add the HTML object, three of which are INPUT and JavaScript tag. Then I add the script code between script tags.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <input type="text" id="numFrom" placeholder="Enter (From) number"> <input type="text" id="numTo" placeholder="Enter (TO) number"> <input type="text" id="numDivider" placeholder="Enter (Divider) number"> <input type="button" value="Calculate" id="calculate"> <div id="result" style="width:150px; border: 1px solid #ddd;position: absolute;top:50px;left:50;padding:20px"> </div> <script> function calulate() { let numFrom=document.getElementById("numFrom").value; let numTo=document.getElementById("numTo").value; let numDivider=document.getElementById("numDivider").value; let result=document.getElementById("result"); result.innerHTML=""; numFrom=Number(numFrom); numTo=Number(numTo); numDivider=Number(numDivider); for(let i=numFrom;i<=numTo;i++) { // if iteration number divisible to numDivider, block works. if(i%numDivider==0) { result.innerHTML+=`${i} is divisble to ${numDivider}<br>`; } } } let btnCalc=document.getElementById("calculate"); btnCalc.onclick=calulate; </script> |
Output: