Thursday, January 8, 2015

Math game JQuery

<style type="text/css">

*{ font-family: verdana; }

</style>

<body></body>

<script type="text/javascript" src="jquery-1.11.1.min.js"></script>

<script type="text/javascript">

$(function() {
   getQuestion();
});

var count = 0,
   results = [];
function getQuestion() {
   count++;
   var operators = ['+', '-', '/', '*']
   var container = $('<div />');
   var val1 = Math.round(Math.random()*5);
   var val2 = Math.round(Math.random()*5);
   var operator = operators[Math.round(Math.random()*(operators.length - 1))];
   var lbl = $('<label />');
   lbl.html(val1 + ' ' + operator + ' ' + val2 + ' = ');
   container.append(lbl);
   var input = $('<input type="text" />');
   container.append(input);
   var btn = $('<input type="button" value="Answer" />');
   var val;
   btn.click(function() {

       results.push({
           number1 : val1,
           number2 : val2,
           answer : input.val()
       });

       input.attr('disabled', true);
       $(this).attr('disabled', true);

       $(this).after(function() {
           if(eval(val1 + operator + val2) == input.val()) return ' Win!';
           return ' Fail!';
       });

       getQuestion();

   });
   container.append(btn);
   $('body').append(container);
}

</script>

Output :)


No comments:

Post a Comment