JavaScript Primers #22

By Joe Burns

http://www.htmlgoodies.com/primers/jsp/article.php/3478351/JavaScript-Primers-22.htm (Back to article)

Use these to jump around or read it all


The Concept
The Script
The Script's Effect
Deconstructing the Script
What You've Learned
Your Assignment


The Concept

This second If example includes a random number, two functions, and introduces If/Else.

If/Else allows the program to decide what to do both when the condition is true and when the condition is false, thus increasing your control of your program.


The Script

<HTML>
<HEAD>
<SCRIPT type="text/javascript">
 function rand()
  {now=new Date()
   num=(now.getSeconds())%10
   num=num+1
   }
 function guessnum()
  {guess=prompt("Your guess?")
   if (eval(guess) == num)
   {alert("YOU GUESSED IT!!")
    rand()
    }
     else
    alert("No.  Try again.")
      }
  </SCRIPT>
</HEAD>
<BODY onLoad="rand()">

  <h2>I'm thinking of a number 
      from 1 to 10</h1>

  <FORM NAME="myform">

    <INPUT TYPE="button" VALUE="Guess" 
       NAME="b1" onClick="guessnum()">

  </FORM>
</BODY>
</HTML>

The Script's Effect

You have to go to this page to see the effect


Deconstructing the Script


What You Have Learned


Your Assignment

Here's a challenge! Use the script above, but alter it so that the user is informed if his or her guess is too high or too low.

HINT! There are only three outcomes possible in that format: Too high, too low, or right on. Think about this: Do you really need an Else statement, or will just a couple more Ifs do it?

Here's the answer to this assignment
(this will open a new window)


The Concept
The Script
The Script's Effect
Deconstructing the Script
What You've Learned
Your Assignment

On To JavaScript Primer #23