jQuery can perform arithmetic easily using arithmetic operators.
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#btn1").click(function(){ var x=10; var y=20; var sum=x+y; var diff=x-y; var product=x*y; var quotient=x/y; $("#firstnum").text(x); $("#secondnum").text(y); $("#sum").text(sum); $("#diff").text(diff); $("#prod").text(product); $("#quo").text(quotient); }); }); </script> </head> <body> <ul> <li id="list1" class="txtclr1" title=" title1"><span>This is item1. My id is= </span> <li id="list2" class="txtclr2" title=" title2"><span>This is item2. My id is= </span> <li id="list3" class="txtclr3" title=" title3"><span>This is item3. My id is= </span> </ul> <button id="btn1">Click to show the IDs and the Title of each item</button> </body> </html>
x=
y=
x+y=
x-y=
x*y=
x/y=
This example shows how to create a math drill using a random number.
We use parseInt(Math.random()*n) to generate random integers between 0 and n. We also use the if else conditional operators to check the answer input by the user.
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#btn2").click(function(){ var x=parseInt(Math.random()*50); var y=parseInt(Math.random()*50); $("#num1").text(x); $("#num2").text(y); }); $("#btn3").click(function(){ var a=$("#num1").text(); var b=$("#num2").text(); var sum=parseInt(a)+parseInt(b); var message; if($("#ans_sum").val()==sum) {message="Correct"+", good job";} else {message="Incorrect"+", please try again";} alert("The answer is "+message); }); }); </script> </head> <body> <h1>Math Drill</h1> <p>x=<span id="num1"></span></p> <p>y=<span id="num2"></span></p> <p>Please enter your answer here:</p> x+y=<input type="text" id="ans_sum"><br> <button id="btn2">Generate Numbers</button> <button id="btn3">Check Answer</button> </body> </html>
x=
y=
Please enter your answer here:
x+y=
Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy