Hello All,

I am a beginner to javascript and would like to learn how to call a function which I implemented, called random, two times, with two seperate div buttons.

I have tried several times to de-bug the code, somehow it still does not work.

My question : Does it have to do with the javascript .click() function?

Thanks,

Code is below :)

JSP:

<%-- 
    Document   : Diagnostic
    Created on : 08-Nov-2010, 10:32:12
    Author     : axa952
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link href="css/Diagnostic.css" rel="stylesheet" type="text/css">
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js">
        </script>

        <script type="text/javascript" src="jquery/Diagnostic.js"></script>

        <title>Diagnostic Page</title>
    </head>
    <body>
        <script type="text/javascript"></script>
        <center>


            <center><h1>Let's see...</h1></center>


            <div id="page-wrap" class ="transbox">

                Add these two numbers:

                <br />


                <button ihttp://www.jobs.ac.uk/job/ABO044/epsrc-funded-phd-studentship/d="getit">Start!</button>

                <div id="n1"></div>
                <div id="n2"></div>
                <div id="plus">
                    <img src="Images/plus.gif" align="center">
                </div>

                <input type="text" id="numCheck" value="?"/>
                <br>
                <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js">
                </script>

                <script type="text/javascript" src="jquery/Diagnostic.js"></script>
                >
                <title>Diagnostic Page< <button id="check"> Check! </button>
                    <div id="result"></div>
            </div>


            <div id="new" class="second">
                Subtract these two numbers:

                >    <br />


                <button id="getit">Pick!</button>

                <div id="n1"></div>
                <div id="n2"></div>
                <div id="plus">
                    <img src="Images/plus.gif" align="center">
                </div>

                <input type="text" id="numCheck" value="?"/>
                <br>
                <button id="check"> Check! </button>
                <div id="result1"></div>
            </div>
        </center>
    </body>
</html>

Java Script

 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


var numRand1;
var numRand2;

function IsNumeric(n){
    return !isNaN(n);
}

$(function random(){
    //when you click on get it, it returns two random numbers between 1 and 100
    $("#getit").click(function() {

        var numLow = 1
        var numHigh = 100

        var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;


        var numRand1 = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
        var numRand2 = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);

        if ((IsNumeric(numLow)) && (IsNumeric(numHigh)) && (parseFloat(numLow) <= parseFloat(numHigh))
            && (numLow != '') && (numHigh != '')) {
            $("#n1").text(numRand1);
            $("#n2").text(numRand2);


        } else {
            $("#n1").text("Careful now...");
            $("#n2").text("Careful now...");


        }

        return false;
    });


    //an input field, clicked
    $("input[type=text]").each(function(){
        $(this).data("click", true);
    });

    $("input[type=text]").focus(function(){

        if ($(this).data("click")) {
            $(this).val("");
            $(this).data("click", false);
            $(this).css("color", "black");
        }

    });
    //when clicked on check, it returns the result of the two random numbers added
    $("#check").click(function(){

        var entered = $("#numCheck").val();
        var result =  numRand1 + numRand2;
        var x = $("#n1").text();
        var xNum = parseFloat(x);
        var y = $("#n2").text();
        var yNum = parseFloat(y);
        if((IsNumeric(xNum)) && (IsNumeric(yNum))){
            xNum !=0;
            yNum !=0
            var result = xNum + yNum;
            if(entered == result){

                $("#result").text("Correct! You got one Point");

            }

            else if( entered !=result){

                $("#result").text( "Wrong! Please try again");
            }
        }

    });

    $("input[type=text]").each(function(){
        $(this).data("click", true);
        $(this).val('');
        $(this).data("click",true);
        $(this).css(color,"Red");
    });


});

CSS

body {
    background-color: green;
    background-image: url("../Images/whale.jpg");
     background-repeat:no-repeat;
     background-position: center top;
     background-size:100%;


}

input[type=text]    { padding: 10px; color: #999; font: bold 20px Helvetica, Sans-Serif;
                      width: 60px; margin: 10px 0; }

#n1       { font-size: 20px; color:red ;
                        }
#plus {position: relative; width: 10px; margin: 0 auto; text-align: left;}


#n2      { font-size: 20px; color:black;
                        }

 #result1      { font-size: 20px; color:Red;}

div.transbox
  {
  width:500px;
  height:300px;
  margin-left:auto;
  margin-right:auto;
  background-color:#ffffff;
  border:1px solid black;
  /* for IE */
  filter:alpha(opacity=60);
  /* CSS3 standard */
  opacity:0.6;
  }
div.transbox
  {
  margin:30px 40px;
  font-weight:bold;
  color:#000000;
  }


  div.second
  {
  width:500px;
  height:300px;
  margin-left:auto;
  margin-right:auto;
  background-color:#ffffff;
  border:1px solid black;
  /* for IE */
  filter:alpha(opacity=60);
  /* CSS3 standard */
  opacity:0.6;
  }
  div.second
  {
  margin:30px 40px;
  font-weight:bold;
  color:#000000;
  }

Hi and welcome to DaniWeb!

When posting code, always make sure you put it between CODE tags:

Some code...

Now onto your problem:

You are starting off with jQuery before you even understand how JavaScript works. jQuery is an extension of JavaScript, making writing it easier.

As you have a question about the JavaScript/HTML of the page, the CSS you added on the bottom is not necessary.

I would recommend starting with JavaScript and then move to jQuery after you understand how it all works.

Below is an example on your project written in clean JavaScript, which is a bit more easy than jQuery:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <title>Asteroids</title>
</head>
<body>

<script type='text/javascript'> 
var PlayerWins = 0; 
var PlayerLosses = 0;

function CreateRandomNumber() {
 
 /* Calculating and returning random number between 0 and 100 */
 return Math.floor(Math.random() * (100 + 1));

}
 
function CheckAnswer() {

 /* Retrieving the two numbers and the player's answer: */
 var Number1 = parseInt(document.getElementById('Number1').innerHTML);
 var Number2 = parseInt(document.getElementById('Number2').innerHTML);
 var Player_Answer = parseInt(document.getElementById('Player_Answer').value);
 
 if (Player_Answer == (Number1 + Number2)) {
 
  /* If the player's answer is correct: */
  
  /* Increasing wins: */
  PlayerWins++;
  
  /* Showing status: */
  alert('Correct answer!\nWins:' + PlayerWins + '\nLosses:' + PlayerLosses);
  
  /* Creating new question: */
  CreateNewQuestion();
  
 } else if (Player_Answer != (Number1 + Number2)) {
 
  /* If the player's answer is incorrect: */
  
  /* Increasing wins: */
  PlayerLosses++;
  
  /* Showing status: */
  alert('Wrong answer!\nWins:' + PlayerWins + '\nLosses:' + PlayerLosses);
  
  /* Creating new question: */
  CreateNewQuestion();
  
 }
 
 
}

function CreateNewQuestion() {

 /* Retrieving new numbers: */
 var New_Number1 = CreateRandomNumber();
 var New_Number2 = CreateRandomNumber();
 
 /* Loading the new numbers into the elements: */
 document.getElementById('Number1').innerHTML = New_Number1;
 document.getElementById('Number2').innerHTML = New_Number2;
 
} 
 
 
/* When the window is loaded, create a new question: */
window.onload=function(){
 CreateNewQuestion();
}

</script>

<form action="" method='post' onsubmit="return false">
 <span id='Number1'></span> + <span id='Number2'></span> = <input size='3' maxlength='3' type='text' id='Player_Answer' /><input type='button' onclick='CheckAnswer()' value='Check answer' />
</form>
</body>
</html>

~G

Hello :)

I must thank you for your help. It has opened my eyes to how much easier java script is than jquery, I cannot understand why they call it "write-less" do-more ? lol :p

If I would like the same function implement a subtraction, a division and a multiplication, what would be a better way to write the code?

Would it be better to have the same function with a different operation( -, * ,/)?

I want the user to stop at 3 strikes with the addition function, and use that number to send it as a string to another java script page so I can determine a user's math level, is this possible?

Thanks again,

I forgot to ask you :)

If I wanted to do that same thing in jquery, how would that be implemented, I will have a try now to see if I can get it done, The problem is, your code works perfect, but Im not sure whether having the javascript code in an html file is feasible design?

I read that javascript files should be separate than jsp/html pages?
Also, regarding the css, I use that to make my work colorful, as it looks good to the user

Thank you again for helping, where can I comment on your help?

Hi and welcome to DaniWeb!

When posting code, always make sure you put it between CODE tags:

Some code...

Now onto your problem:

You are starting off with jQuery before you even understand how JavaScript works. jQuery is an extension of JavaScript, making writing it easier.

As you have a question about the JavaScript/HTML of the page, the CSS you added on the bottom is not necessary.

I would recommend starting with JavaScript and then move to jQuery after you understand how it all works.

Below is an example on your project written in clean JavaScript, which is a bit more easy than jQuery:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <title>Asteroids</title>
</head>
<body>

<script type='text/javascript'> 
var PlayerWins = 0; 
var PlayerLosses = 0;

function CreateRandomNumber() {
 
 /* Calculating and returning random number between 0 and 100 */
 return Math.floor(Math.random() * (100 + 1));

}
 
function CheckAnswer() {

 /* Retrieving the two numbers and the player's answer: */
 var Number1 = parseInt(document.getElementById('Number1').innerHTML);
 var Number2 = parseInt(document.getElementById('Number2').innerHTML);
 var Player_Answer = parseInt(document.getElementById('Player_Answer').value);
 
 if (Player_Answer == (Number1 + Number2)) {
 
  /* If the player's answer is correct: */
  
  /* Increasing wins: */
  PlayerWins++;
  
  /* Showing status: */
  alert('Correct answer!\nWins:' + PlayerWins + '\nLosses:' + PlayerLosses);
  
  /* Creating new question: */
  CreateNewQuestion();
  
 } else if (Player_Answer != (Number1 + Number2)) {
 
  /* If the player's answer is incorrect: */
  
  /* Increasing wins: */
  PlayerLosses++;
  
  /* Showing status: */
  alert('Wrong answer!\nWins:' + PlayerWins + '\nLosses:' + PlayerLosses);
  
  /* Creating new question: */
  CreateNewQuestion();
  
 }
 
 
}

function CreateNewQuestion() {

 /* Retrieving new numbers: */
 var New_Number1 = CreateRandomNumber();
 var New_Number2 = CreateRandomNumber();
 
 /* Loading the new numbers into the elements: */
 document.getElementById('Number1').innerHTML = New_Number1;
 document.getElementById('Number2').innerHTML = New_Number2;
 
} 
 
 
/* When the window is loaded, create a new question: */
window.onload=function(){
 CreateNewQuestion();
}

</script>

<form action="" method='post' onsubmit="return false">
 <span id='Number1'></span> + <span id='Number2'></span> = <input size='3' maxlength='3' type='text' id='Player_Answer' /><input type='button' onclick='CheckAnswer()' value='Check answer' />
</form>
</body>
</html>

~G

If you want to add other operators such as - / % etc, you need to replace the normal + in the form into:

<span id='Operator'></span>

And then adjust the CheckAnswer() function by adding the following to the part where you retrieve the values:

var Operator = document.getElementById('Operator').innerHTML;

Then you adjust the part where it checks for the correct answer:

if (Operator == "+") {
 ... Check the answer with the addition value
} else if (Operator == "-") {
 ... Check the answer with the substraction value
}

And so on for every operator!

But this also means you will need to adjust the CreateNewQuestion() function, as this now will also need to randomly pick a operator, so you will need to add a function to the entire script named CreateRandomOperator() which calculates a random number (for example 0-2) then returns a operator depending on what number is picked (so 0 = addition (+), 1 = substraction (-), 2 = division (/) etc...) and return that.

When you made that function, you need to make a adjustment to the CreateNewQuestion() :

function CreateNewQuestion() {

 var New_Number1 = CreateRandomNumber();
 var New_Number2 = CreateRandomNumber();
 var New_Operator = CreateRandomOperator();
 
 /* Loading the new numbers into the elements: */
 document.getElementById('Number1').innerHTML = New_Number1;
 document.getElementById('Number2').innerHTML = New_Number2;
 document.getElementById('Operator').innerHTML = New_Operator;

}

The above is the answer to your first post, to answer your second question: you can include JavaScripts in your html page by adding the following in either the <body> or the <head> tag:

<script type='text/javascript' src='MyScript.js'></script>

And then MyScript.js looks exactly like your previous code:

var SomeVar = 0;
var SomeVar2 = 3;

function SomeFunction() {
 .... Does something...
}

~G

Thanks again, that was very helpful,

I just started making two functions,

One is get score, which loops on Player wins and gets the number of hits when the answer is true and returns the score, which should not be greater than 4.

the other is check level, if the user solves 3 or more, then I would like to add a link for the user to go to the next stage , this is my code, its worthless, i know, such a noob

function getScore(){
    var score;
    for(int score = 0; score<=4;score++){
        if(PlayerWins()){
            score = score +1;
        }

    }
    return score;


}

function checkLevel(){

    if(getScore()>=3){
        alert("Go to the next Stage! link added")
    }
    else{
        alert("You are in the Alpha stage, lets work on addition");
    }
}

If you want to add other operators such as - / % etc, you need to replace the normal + in the form into:

<span id='Operator'></span>

And then adjust the CheckAnswer() function by adding the following to the part where you retrieve the values:

var Operator = document.getElementById('Operator').innerHTML;

Then you adjust the part where it checks for the correct answer:

if (Operator == "+") {
 ... Check the answer with the addition value
} else if (Operator == "-") {
 ... Check the answer with the substraction value
}

And so on for every operator!

But this also means you will need to adjust the CreateNewQuestion() function, as this now will also need to randomly pick a operator, so you will need to add a function to the entire script named CreateRandomOperator() which calculates a random number (for example 0-2) then returns a operator depending on what number is picked (so 0 = addition (+), 1 = substraction (-), 2 = division (/) etc...) and return that.

When you made that function, you need to make a adjustment to the CreateNewQuestion() :

function CreateNewQuestion() {

 var New_Number1 = CreateRandomNumber();
 var New_Number2 = CreateRandomNumber();
 var New_Operator = CreateRandomOperator();

 /* Loading the new numbers into the elements: */
 document.getElementById('Number1').innerHTML = New_Number1;
 document.getElementById('Number2').innerHTML = New_Number2;
 document.getElementById('Operator').innerHTML = New_Operator;

}

The above is the answer to your first post, to answer your second question: you can include JavaScripts in your html page by adding the following in either the <body> or the <head> tag:

<script type='text/javascript' src='MyScript.js'></script>

And then MyScript.js looks exactly like your previous code:

var SomeVar = 0;
var SomeVar2 = 3;

function SomeFunction() {
 .... Does something...
}

G

Sorry,

I just realized since you already initiated a variable called player wins, I might as well just do this:

function checkLevel(){
    if(PlayerWins >=3){
        alert("Excellent, go to the next stage test");
    }
    else{
        alert("You are in Alpha level, lets work on addition and subtraction");
    }
    return PlayerWins;


}

Thanks again, that was very helpful,

I just started making two functions,

One is get score, which loops on Player wins and gets the number of hits when the answer is true and returns the score, which should not be greater than 4.

the other is check level, if the user solves 3 or more, then I would like to add a link for the user to go to the next stage , this is my code, its worthless, i know, such a noob

function getScore(){
    var score;
    for(int score = 0; score<=4;score++){
        if(PlayerWins()){
            score = score +1;
        }

    }
    return score;


}

function checkLevel(){

    if(getScore()>=3){
        alert("Go to the next Stage! link added")
    }
    else{
        alert("You are in the Alpha stage, lets work on addition");
    }
}

end quote.

Sorry Graphix,

I got that part to work,
I just modified the part in the create question to give me an alert.
I'll post more questions if I need to,

Thanks a million

Sorry, I just realized since you already initiated a variable called player wins, I might as well just do this:

function checkLevel(){
if(PlayerWins >=3){
alert("Excellent, go to the next stage test");
}
else{
alert("You are in Alpha level, lets work on addition and subtraction");
}
return PlayerWins;
}

Hi Graphix,

Thanks for your reply,

I took your advice on the random operator stuff and here is what I did,
problem is the random numbers are not showing up, nor the operator

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Asteroids</title>
    </head>
    <body>
        <link href="css/Diagnostic.css" rel="stylesheet" type="text/css">

            <script type='text/javascript'>
                var PlayerWins = 0;
                var PlayerLosses = 0;

                function CreateRandomNumber() {

                    /* Calculating and returning random number between 0 and 100 */
                    return Math.floor(Math.random() * (100 + 1));

                }
                function CreateRandomOperator(){
                        //creat random number between 0 and 1
                        var Operator;
                        var val = Math.floor(Math.random() * (1 + 1));
                        if(val ==0){
                            Operator = "+";
                        }
                        else if(val ==1){
                            Operator = "-";
                        }
                        return Operator;
                    }

                function CheckAnswer() {

                    /* Retrieving the two numbers and the player's answer: */
                    var Number1 = parseInt(document.getElementById('Number1').innerHTML);
                    var Number2 = parseInt(document.getElementById('Number2').innerHTML);
                    var Operator = document.getElemendById('Operator').innerHTML;
                    var Player_Answer = parseInt(document.getElementById('Player_Answer').value);
                    if (Operator == '+') {
                        if(Player_Answer == Number1 + Number2){

                            PlayerWins++
                             /* Showing status: */
                        alert('Correct answer!nWins:' + PlayerWins + 'nLosses:' + PlayerLosses);
                        if(PlayerWins >=4){
                        alert("Excellent, Let's move to the next stage");
                        CreateNewQuestion();


                    }
                        else if(PlayerLosses > 1){
                            alert("You belong to the Alpha stage, Sign up below");

                        }


                        else if(Player_Answer != Number1 + Number2){
                            PlayerLosses++;
                            alert('Wrong answer!nWins:' + PlayerWins + 'nLosses:' + PlayerLosses);
                        }
                        }
                    }
                     else if(Operator == '-'){
                        if(Player_Answer == Number1-Number2){
                            PlayerWins++
                        }
                        else if(Player_Answer !=Number1-Number2){
                            PlayerLosses++
                        }
                    }

                    function CreateNewQuestion() {

                        /* Retrieving new numbers: */
                        var New_Number1 = CreateRandomNumber();
                        var New_Number2 = CreateRandomNumber();
                        var Operator = CreateRandomOperator();

                        /* Loading the new numbers into the elements: */
                        document.getElementById('Number1').innerHTML = New_Number1;
                        document.getElementById('Number2').innerHTML = New_Number2;
                        document.getElementById('Operator').innerHTML = Operator;

                    }

                    /* When the window is loaded, create a new question: */
                    window.onload=function(){
                        CreateNewQuestion();


                    }

            </script>

            <form action="" method='post' onsubmit="return false">
                <span id='Number1'></span> <span id='Operator'></span> <span id='Number2'></span> = <input size='3' maxlength='3' type='text' id='Player_Answer' />
                <input type='button' onclick='CheckAnswer()' value='Check answer' />
                <br>

            </form>
    </body>
</html>

The code doesnt look properly like you guys get it done with the lines and dots, is my CODE-wrong

Hi and welcome to DaniWeb!

When posting code, always make sure you put it between CODE tags:

Some code...

Now onto your problem:

You are starting off with jQuery before you even understand how JavaScript works. jQuery is an extension of JavaScript, making writing it easier.

As you have a question about the JavaScript/HTML of the page, the CSS you added on the bottom is not necessary.

I would recommend starting with JavaScript and then move to jQuery after you understand how it all works.

Below is an example on your project written in clean JavaScript, which is a bit more easy than jQuery:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <title>Asteroids</title>
</head>
<body>

<script type='text/javascript'> 
var PlayerWins = 0; 
var PlayerLosses = 0;

function CreateRandomNumber() {

 /* Calculating and returning random number between 0 and 100 */
 return Math.floor(Math.random() * (100 + 1));

}

function CheckAnswer() {

 /* Retrieving the two numbers and the player's answer: */
 var Number1 = parseInt(document.getElementById('Number1').innerHTML);
 var Number2 = parseInt(document.getElementById('Number2').innerHTML);
 var Player_Answer = parseInt(document.getElementById('Player_Answer').value);

 if (Player_Answer == (Number1 + Number2)) {

  /* If the player's answer is correct: */

  /* Increasing wins: */
  PlayerWins++;

  /* Showing status: */
  alert('Correct answer!nWins:' + PlayerWins + 'nLosses:' + PlayerLosses);

  /* Creating new question: */
  CreateNewQuestion();

 } else if (Player_Answer != (Number1 + Number2)) {

  /* If the player's answer is incorrect: */

  /* Increasing wins: */
  PlayerLosses++;

  /* Showing status: */
  alert('Wrong answer!nWins:' + PlayerWins + 'nLosses:' + PlayerLosses);

  /* Creating new question: */
  CreateNewQuestion();

 }


}

function CreateNewQuestion() {

 /* Retrieving new numbers: */
 var New_Number1 = CreateRandomNumber();
 var New_Number2 = CreateRandomNumber();

 /* Loading the new numbers into the elements: */
 document.getElementById('Number1').innerHTML = New_Number1;
 document.getElementById('Number2').innerHTML = New_Number2;

} 


/* When the window is loaded, create a new question: */
window.onload=function(){
 CreateNewQuestion();
}

</script>

<form action="" method='post' onsubmit="return false">
 <span id='Number1'></span> + <span id='Number2'></span> = <input size='3' maxlength='3' type='text' id='Player_Answer' /><input type='button' onclick='CheckAnswer()' value='Check answer' />
</form>
</body>
</html>

end quote.

You need to encase your code in code tags, one that opens, one that closes (without the spaces between the []):

[CODE ] Some code.... [/CODE ]

Anyway, on to your code:

  • You misspelled getElementById by changing the 't' into a 'd'
  • You kind of messed up the brackets in the CheckAnswer() function

The code was written OK, so my complements for that ;) I adjusted the code a bit so that it is more commented and spaced:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Math Quiz</title>
</head>
<body>

<script type='text/javascript'>
var PlayerWins = 0;
var PlayerLosses = 0;

function CreateRandomNumber() {

  /* Calculating and returning random number between 0 and 100 */
  return Math.floor(Math.random() * (100 + 1));

}

function CreateRandomOperator(){

  /* Calculate random number between 0 and 1 */

  var Operator = "";

  var val = Math.floor(Math.random() * (1 + 1));

  if(val == 0) {
    Operator = "+";
  } else if (val == 1) {
    Operator = "-";
  }

  return Operator;

}

function CheckAnswer() {

  /* Retrieving the two numbers and the player's answer: */
  var Number1 = parseInt(document.getElementById('Number1').innerHTML);
  var Number2 = parseInt(document.getElementById('Number2').innerHTML);
  var Operator = document.getElementById('Operator').innerHTML;
  var Player_Answer = parseInt(document.getElementById('Player_Answer').value);

  /* First you check whether the answer is correct: */

  if (Operator == '+') {

    if(Player_Answer == Number1 + Number2){

        PlayerWins++

        /* Showing status: */
        alert('Correct answer!\nWins:' + PlayerWins + '\nLosses:' + PlayerLosses);

    } else if (Player_Answer != Number1 + Number2){

        PlayerLosses++;

        /* Showing status: */
        alert('Wrong answer!\nWins:' + PlayerWins + '\nLosses:' + PlayerLosses);

    }

  } else if (Operator == "-") {

     /* This part I am going to leave blank for you to fill in... */
     alert('You answered a substraction sum!');

  }

  /* Checking whether the user can move to the next stage: */

  if ( PlayerWins >= 4 ){

    alert("Excellent, Let's move to the next stage");
    CreateNewQuestion();

    /* Perhaps you want to do something if the player has 5 wins or more like making it more difficult equations? */

  } else if (PlayerLosses > 1) {

    alert("You belong to the Alpha stage, Sign up below");

    /* Perhaps you should call a function here that hides the form or something? */

  } else {

    /* Default, just create a new question: */
    CreateNewQuestion();

  }

}

function CreateNewQuestion() {

  /* Retrieving new numbers: */
  var New_Number1 = CreateRandomNumber();
  var New_Number2 = CreateRandomNumber();
  var Operator = CreateRandomOperator();

  /* Loading the new numbers into the elements: */
  document.getElementById('Number1').innerHTML = New_Number1;
  document.getElementById('Number2').innerHTML = New_Number2;
  document.getElementById('Operator').innerHTML = Operator;

}

/* When the window is loaded, create a new question: */
window.onload=function(){
CreateNewQuestion();
} 

alert('Script is working!');
</script>

<form action="" method='post' onsubmit="return false">
<span id='Number1'></span> <span id='Operator'></span> <span id='Number2'></span> = <input size='3' maxlength='3' type='text' id='Player_Answer' />
<input type='button' onclick='CheckAnswer()' value='Check answer' />
<br>

</form>
</body>
</html>

I left out the part in which you calculate the subtraction of two numbers so you can fill the code in. Also, I saw in your previous code that you removed the indent of the code and some comments. This is highly not recommended as it makes the code unclear...

A few tips when programming:

  • Always use a syntax highlighting editor (http://notepad-plus-plus.org/download)
  • Use excessive commenting
  • Indent everything between brackets
  • Add alerts when the script doesn't work, starting with one on the bottom that says 'Script is working!' so that you know you did not make any typos, but also in between code. A example:

    function DoSomething() {
    
     /* If the function is called at all, this alert is shown: */
     alert('Function called!'); 
    
     var x = document.getElementById('form_x').value;
    
     /* If the ID form_x does not exist, this alert is not shown: */
     alert('Value of x: ' + x);
    
     x = x + 4;
    
     alert('Result of x: ' + x);
    
     return x;
    
    }
    
    window.onload=function(){
    DoSomething();
    } 
    
    /* This alert will fail if a bracket is not closed, a ; is forgotten etc. */
    alert('No typos made! Script is working!');
    

~G

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.